natli
natli

Reputation: 3822

Regex groups not working

I am trying to match & group (any phrase)##date##(any phrase), but val1 and val2 are empty.

Console.WriteLine("Subject: "+line);
Match match = Regex.Match(line, "(.)"+Regex.Escape("##date##")+"(.)", RegexOptions.IgnoreCase);
string val1 = match.Groups[1].Value;
string val2 = match.Groups[2].Value;
Console.WriteLine("Line#{0}: {1} Date: {2}", ++lineNo, val1, val2);

Console:

Subject: http://www.website.com/url/is/masked.htm ##date## 3
Line#25:   Date: 

Isn't a dot supposed to match anything?

Upvotes: 0

Views: 95

Answers (2)

Michael Liu
Michael Liu

Reputation: 55499

A dot matches a single character other than a newline. In your case, it matched the space before and after ##date##. Use the following regular expression instead:

Match match = Regex.Match(line, "(.*) ##date## (.*)", RegexOptions.IgnoreCase);

This matches the entire phrases before and after ##date##, excluding the single spaces on either side.

Output:

Line#25: http://www.website.com/url/is/masked.htm Date: 3

Upvotes: 2

kirilloid
kirilloid

Reputation: 14304

Dot matches a single symbol and in your example ##date## is surrounded by two spaces. Hence your group mathces are space and space, which looks like "nothing".

Upvotes: 2

Related Questions