0

I am trying to match the below text using Regex,

"1bbl" 2bbl "is as" 0.22 "3"

When I match I am not getting the output as expected in my list.

string val = "\"1bbl\" 2bbl \"is as\" 0.22 \"3\"";
var reg = new Regex(@"([a-z0-9\s]+)");
Match match = reg.Match(val);
List<string> list = new List<string>();
while (match.Success)
{
    list.Add(match.ToString());
    match = match.NextMatch();
}

Current Output:

"1bbl"
" 2bbl "
"is as"
" 0"
"22 "
"3"

Expected Output:

"1bbl"
"2bbl"
"is as"
"0.22"
"3"
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Edwin Vivek N
  • 564
  • 8
  • 28
  • I've edited out unrelated references to XML - feel free to revert... In either case please explain why `"is as"` should be selected as a string. – Alexei Levenkov Mar 20 '15 at 06:11

3 Answers3

0

You need to include the pattern for matching decimal numbers also.

System.Text.RegularExpressions.Regex(@"\b(?:\d+\.\d+|[a-z\s0-9]+)\b");

\b at the start and at the end helps to avoid matching of unnecessary leading and trailing spaces.

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Your regex ([a-z0-9\s]+) does not capture special characters. Hence, it doesn't capture the decimal point.

You might want to add the special characters that you need to capture inside the regex. Say, you need to allow'@', '#' and '.' to be captured, then you regex will be:

System.Text.RegularExpressions.Regex(@"([a-z0-9\s@#\.]+)")

Since the point '.' has a special meaning in regex, we need to use a backlash, hence '\.' .

Akshay Rane
  • 403
  • 4
  • 13
0

Since it looks like you are matching a space delimited string with quotes used as text qualifiers, you might want to use a regex like the below instead:

@"""[^""]+""|[^""\s]+"

That is, try to match any text field, grab everything inside the text qualifiers (quotes) ""([^""]+)"", else, grab everything using space as delimiter ([^""\s]+).

ideone demo

Though if you don't want to get the quotes in the match, you can use named capture groups, for example:

@"""(?<1>[^""]+)""|(?<1>[^""\s]+)"

ideone demo

Jerry
  • 70,495
  • 13
  • 100
  • 144