Question

Removing characters from a string

Asked by: SeanNij

Hi all,

I have written some code to export a recordset to a text files (docmd.transfertext) but in this line it "builds" the text file's filename from a couple of fields on the order form. If the user puts in a "/" or "?" etc in his order no, the filename becomes invalid - is there anyway i can "strip" the orderno field of "invalid filename characters" or only characters A-Z, 0-9 a-z, etc? so at least i keep the just of the orderno?

Thanks
Sean

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-06-27 at 20:16:11ID22663130
Tags

remove

,

string

,

characters

,

from

Topics

Microsoft Visual Basic.Net

,

Microsoft Access Database

Participating Experts
6
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. strip characters
    A file is open as Random. I need to look at a field and strip the alphas out so all I have left are numerics. I have created a user defined type, and can get to the field this way. I am at a loss as to how to get the program to read one character at a time and get rid of t...
  2. Strip Characters: Better routine
    WHAT I NEED: A BETTER WAY TO DO THIS CODE I also would like to strip these characters from field called, "FINALDESC"-TEXT FIELD FROM A TABLE CALLED TBLDATA ! @ # % & * ( ) _ + ' ; : " \ / ? < > - ANY SUGGESTIONS Dim MyDB As Database, Myset As...
  3. Stripping a character from a string
    I simply need to strip a character, which is declared as a variable, from a string. So if there's a string variable containing "Test123", I'd want it to strip all occurences of 2, leaving "Test13" Any help would be appreciated! Thanks
  4. C# strip out bad characters?
    I am going to have a string with is going to have many special characters in it . I want to strip out all the non alpha characters Ex: So'Home I want to go through this string, stip out anything that is not [a-z] and save it as.... SoHome.. Quickest way to do t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Raynard7Posted on 2007-06-27 at 20:21:56ID: 19377962

Hi,

Use a regular expression to replace everything that does not match,

try http://www.thescripts.com/forum/thread369354.html for a working example of this.

 

by: DatabaseMXPosted on 2007-06-27 at 20:37:42ID: 19378021

If you are doing the entry in a text box, then a simple Input Mask will work for those characters ... here are the details ... customize as needed:
------------------------------------------
InputMask Property
See AlsoApplies ToExampleSpecificsYou can use the InputMask property to make data entry easier and to control the values users can enter in a text box control. Read/write String.

expression.InputMask
expression    Required. An expression that returns one of the objects in the Applies To list.

Remarks
Input masks are helpful for data-entry operations such as an input mask for a Phone Number field that shows you exactly how to enter a new number: (___) ___-____. It is often easier to use the Input Mask Wizard to set the property for you.

The InputMask property can contain up to three sections separated by semicolons (;).

Section Description
First Specifies the input mask itself; for example, !(999) 999-9999. For a list of characters you can use to define the input mask, see the following table.
Second Specifies whether Microsoft Access stores the literal display characters in the table when you enter data. If you use 0 for this section, all literal display characters (for example, the parentheses in a phone number input mask) are stored with the value; if you enter 1 or leave this section blank, only characters typed into the control are stored.
Third Specifies the character that Microsoft Access displays for the space where you should type a character in the input mask. For this section, you can use any character; to display an empty string, use a space enclosed in quotation marks (" ").


In Visual Basic you use a string expression to set this property. For example, the following specifies an input mask for a text box control used for entering a phone number:

Forms!Customers!Telephone.InputMask = "(###) ###-####"
            
When you create an input mask, you can use special characters to require that certain data be entered (for example, the area code for a phone number) and that other data be optional (such as a telephone extension). These characters specify the type of data, such as a number or character, that you must enter for each character in the input mask.

You can define an input mask by using the following characters.

Character Description
0 Digit (0 to 9, entry required, plus [+] and minus [] signs not allowed).
9 Digit or space (entry not required, plus and minus signs not allowed).
# Digit or space (entry not required; spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved; plus and minus signs allowed).
L Letter (A to Z, entry required).
? Letter (A to Z, entry optional).
A Letter or digit (entry required).
a Letter or digit (entry optional).
& Any character or a space (entry required).
C Any character or a space (entry optional).
. , : ; - / Decimal placeholder and thousand, date, and time separators. (The actual character used depends on the settings in the Regional Settings Properties dialog box in Windows Control Panel).
< Causes all characters to be converted to lowercase.
> Causes all characters to be converted to uppercase.
! Causes the input mask to display from right to left, rather than from left to right. Characters typed into the mask always fill it from left to right. You can include the exclamation point anywhere in the input mask.
\ Causes the character that follows to be displayed as the literal character (for example, \A is displayed as just A).

Note   Setting the InputMask property to the word "Password" creates a password-entry control. Any character typed in the control is stored as the character but is displayed as an asterisk (*). You use the Password input mask to prevent displaying the typed characters on the screen.

For a control, you can set this property in the control's property sheet. For a field in a table, you can set the property in table Design view (in the Field Properties section) or in Design view of the Query window (in the Field Properties property sheet ).

You can also set the InputMask property by using a macro or Visual Basic.

When you type data in a field for which you've defined an input mask, the data is always entered in Overtype mode. If you use the BACKSPACE key to delete a character, the character is replaced by a blank space.

If you move text from a field for which you've defined an input mask onto the Clipboard, the literal display characters are copied, even if you have specified that they not be saved with data.


Note  Only characters that you type directly in a control or combo box are affected by the input mask. Microsoft Access ignores any input masks when you import data, run an action query, or enter characters in a control by setting the control's Text property in Visual Basic or by using the SetValue action in a macro.


When you've defined an input mask and set the Format property for the same field, the Format property takes precedence when the data is displayed. This means that even if you've saved an input mask, the input mask is ignored when data is formatted and displayed. The data in the underlying table itself isn't changed; the Format property affects only how the data is displayed.

Example
The following table shows some useful input masks and the type of values you can enter in them.

Input mask Sample values
(000) 000-0000 (206) 555-0248
(999) 999-9999 (206) 555-0248
 ( ) 555-0248
(000) AAA-AAAA (206) 555-TELE
#999 20
 2000
>L????L?000L0 GREENGR339M3
 MAY R 452B7
>L0L 0L0 T2F 8M4
00000-9999 98115-
 98115-3007
>L<?????????????? Maria
 Brendan
SSN 000-00-0000 SSN 555-55-5555
>LL00000-0000 DB51392-0493

-----------------
mx

 

by: SeanNijPosted on 2007-06-27 at 20:44:29ID: 19378040

DatabaseMX, wow = thanks for that.

However, the user is allowed to type anything in that box. so i cant use an input mask. I just want to take the alphanumeric character out of whatever he has typed so we got easy identification on the saved text file. So of the reps user "orderdesc/ownorderef" as their order no and obviously as a filename the "/" causes chaos.

 

by: capricorn1Posted on 2007-06-27 at 20:51:18ID: 19378059

place this codes in a module

Option Explicit
Private Declare Function IsCharAlphaNumeric _
        Lib "user32" Alias "IsCharAlphaNumericA" _
        (ByVal byteChar As Byte) As Long

Public Function CleanText(InText As String) As String
Dim j As Long, sRet As String
    For j = 1 To Len(InText)
        If IsCharAlphaNumeric(Asc(Mid(InText, j, 1))) = 1 Then
            sRet = sRet & Mid(InText, j, 1)
        End If
    Next
    CleanText = Trim(sRet)
End Function

to use

CleanText("fileName")


cleantext("/abcde/1/ff.")

abcde1ff       << result

 

by: etshermanPosted on 2007-06-27 at 20:55:54ID: 19378074

I kind of agree with DatabaseMX ...

Why not control what the user input into the field/table rather that allow anything to be input then have the task of stripping it back out.

Just my $.02

ET

 

by: SeanNijPosted on 2007-06-27 at 21:04:25ID: 19378096

Esterman - i would like too, but the people responsible for capturing the data have their own little "systems" and we all know what the average user opinion of CHANGE is like....

Having a look at the regex (requires another linked reference which can be a nightmare on its own) and gonna try capricorn1's idea.

Thanks all.

 

by: icrPosted on 2007-06-28 at 02:56:45ID: 19379235

The simplest way I think is to do this:

Dim filePath As String = "This""<Needs"
Dim fileName As String = "Clea|>ning"
Dim invalidChar As Char
For Each invalidChar In Path.GetInvalidPathChars()
    filePath = filePath.Replace(invalidChar.ToString(), "")
Next invalidChar
For Each invalidChar In Path.GetInvalidFileNameChars()
    fileName = fileName.Replace(invalidChar.ToString(), "")
Next invalidChar
Console.WriteLine("C:\" + filePath + "\" + fileName)

Though there is probably a more efficient way of looping through and stripping the characters.

 

by: FernandoSotoPosted on 2007-06-28 at 07:13:11ID: 19380865

Hi SeanNij;

The following code will do what you need with the file name using regular expressions.

Imports System.Text.RegularExpressions

        ' The Regex pattern to remove invalid characters from the file name
        Dim pattern As String = "(\*|/|\?|<|>|:|\\|\x22|\+|,|;|=|\[|\]|\|)+"
        ' Test file name with invalid characters
        Dim Filename As String = "T*h/en\a?m<eo>f:F""il+e,;1=[23].d|at"

        ' File name should now be valid
        Filename = Regex.Replace(Filename, pattern, "")

        MessageBox.Show(Filename)

Filename will now have "ThenameofFile123.dat"

Fernando

 

by: icrPosted on 2007-06-28 at 07:38:40ID: 19381135

It's generally bad practice to use magic constants ( http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_code ). If you decide to use Mono to move to another platform, or Microsoft decide to become more lenient or strict with what characters they allow (unlikely but possible) then you will come unstuck.

Even if these aren't an issue it's generally considered bad practice. If you are using a regex you should build it using Path.GetInvalidPathChars() and Path.GetInvalidFileNameChars().

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...