tags:

views:

279

answers:

1

Hi,

I'm trying to create a regex to tokenize a string. An example of the string is

ExeScript.ps1 $1, $0,%1, %3

Or it may be carelessly typed in as . ExeScript.ps1       $1, $0,%1, %3`

I use a simple regex string.

Regex RE = new Regex(@"[\s,\,]");
return (RE.Split(ActionItem));

I get a whole bunch of zeros between the script1.ps1 and the $1 When it is evenly spaced, as in first example I get no space between the script1.ps1 and the $1.

What am I doing wrong. How do I supress whitespace and ensure each array cell has a value in it which is now a whitespace.

Bob.

+2  A: 

Try this regex:

Regex RE = new Regex(@"[\s,\,]+");

The + makes the delimiter "one or more" of the previous items. This may help, but it won't detect the situation of two commas (it would interpret it as one delimiter, which may not be what you want). Another possibility would be:

Regex RE = new Regex(@"\s*,\s*");

which is zero or more spaces, followed by a comma, followed by zero or more spaces.

You may also have to decide how you want to handle inputs such as:

foo, ,bar

which you might view as a list of three items, the second of which is a single space.

Greg Hewgill
Thanks Greg, I almost had it, but the plus was inside the square brackets. I hate regex. It works perfectly, even fixes multiple commasBob.
scope_creep