tags:

views:

37

answers:

2

I have a string ABCD:10,20,,40;1/1;1/2,1/3,1/4 I want to split the string into the following parts:

ABCD -- splited by :

10,20,,40 -- splited by ;

1/1 -- splited by ;

1/2,1/3,1/4 -- splited by ;

Why the following regular expression does not work for me ?

string txt = @"ABCD:10,20,,40;1/1;1/2,1/3,1/4";

Regex reg = new Regex(@"\b(?<test>\w+):(?<com>\w+);(?<p1>\w+);(?<p2>\w+)");
Match match = reg.Match(txt);
+4  A: 

The , and / character will not be matched by \w. \w matches letters, numbers, and underscores only.

It's better to use [^;]+ to get everything but ;'s for what you are trying to do:

new Regex(@"\b(?<test>\w+):(?<com>[^;]+);(?<p1>[^;]+);(?<p2>[^;]+)");

I left the test capture group alone, assuming it would always be [a-zA-Z0-9_]+.

gnarf
+1  A: 

If your tokens can't contain : and ; themselves, you could just split on the regex: [:;]

Bart Kiers