|
-
Sep 2nd, 2010, 04:33 PM
#1
Thread Starter
Lively Member
Regular Expressions..
:
I've used regular expressions in the past, but I can't figure something out that should not be so hard...
I have an app that parses a .csv file and replaces certain characters (commas). Here's an example..
Code:
item1,item2,item3,fruits are apples, oranges, grapes. Squash is a vegetable, not a fruit.
What my app does is search each line between character1 and character18 and replace all "," with "~".
Does anyone know how this is done through regular expressions? I'm brushing up on it, but thought I'd post here in hopes of saving a little time.
TIA!
-
Sep 2nd, 2010, 04:44 PM
#2
Re: Regular Expressions..
I can show you, but first I'm going to not recommend it.
Regular expressions are a pretty big tool; when you use a regex you essentially ask the computer at runtime to fire up code that compiles the regex into something that does the parsing for you. You can mitigate this overhead, but the fact that it's there makes regex somewhat inappropriate for lightweight tasks.
This, in addition to the notion that a regex is generally harder to understand, makes regex a poor tool for very simple text replacement tasks. String.Replace() does a good job for simple replacements:
Code:
Dim myString As String = "asdf, jkl, qwerty"
myString = myString.Replace(",", "~")
If you insist, have a look at Regex.Replace(). You need three things to use Regex.Replace():
- The pattern that defines what should be replaced.
- The string that will have things replaced.
- The string that will replace the things that match the pattern.
In your case, you have a string where you want to replace "," with "~". Usage might look like this:
Code:
Dim myString As String = "asdf, jkl, qwerty"
Dim regex As New Text.RegularExpressions.Regex(",")
myString = regex.Replace(myString, "~")
Honestly, it's a little more work for such a simple substitution. I'd recommend reserving regex for more complicated replacement tasks, like "replace ',,' but leave ',,,' alone" or something crazy like "Foo value = new Foo();" to "Dim value As New Foo()".
-
Sep 2nd, 2010, 05:51 PM
#3
Fanatic Member
Re: Regular Expressions..
Totally agree with Sitten and was exactly what I was going to recommend for the same reasons.
Visual Studio 2010 Professional | .NET Framework 4.0 | Windows 7
SERYSOFT.COM :: SysPad - Folder Management Program - Please comment HERE if you find this program useful, have ideas, or know of any bugs.
[Very useful for IT/DP departments where many folders are consistently accessed. Also contains a scratchpad window for quick access to notes.]
[.NET and MySQL Quick Guide]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|