469,586 Members | 2,185 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,586 developers. It's quick & easy.

Regex, matching with required and some optional

I'm new to C# so am not completely familiar with its regular expression flavor and I don't understand why I can't get this to work. I set the singline | ignorecase options in the regex ctor.

Given the following example data

Expand|Select|Wrap|Line Numbers
  1. <tr>test1:567.98  </tr>
  2. <tr>test1:567.98    test2:999  </tr>
  3. <tr>test1:267.98    test2:959  </tr>
  4. <tr>test1:547.98    test2:699  </tr>
  5. <tr>test1:567.98  </tr>
I want a regex that will match each <tr></tr> block (which I'll call lines from now on) and capture the numbers after test1 and test2, if it's there, in named groups. In other words, I want
Expand|Select|Wrap|Line Numbers
  1. Debug.Print(Match.Groups["t1"].Value + "--" + Match.Groups["t2"].Value) // should equal 567.98-- for line #1
  2. Debug.Print(Match.Groups["t1"].Value + "--" + Match.Groups["t2"].Value) // should equal 567.98--999 for line #2
  3. Debug.Print(Match.Groups["t1"].Value + "--" + Match.Groups["t2"].Value) // should equal 267.98--959 for line #3 ... etc
so I attempted:

Expand|Select|Wrap|Line Numbers
  1. <tr>.*?test1:(?<t1>[\d.,]+).*?(?:test2:(?<t2>[\d]+))?.*?</tr>
but Match.Groups["t2"] is empty, even though that particular match shows the entire line 2 (including test2:999)

so then I tried an alternation:

Expand|Select|Wrap|Line Numbers
  1. <tr>.*?test1:(?<t1>[\d.,]+).*?(?:(?:test2:(?<t2>[\d]+))|)?.*?</tr>
same result...

I tried a few other patterns and they would either return only the first and last line, or only those lines where test2 was present. I tried many permutations (various groupings with named or unnamed), lookbehinds, etc... I just don't get it.

I have watch statements on all possible groups (i.e: debug.print(m.Groups[0] ... m.Groups[10]) and I can *never* match anything related to test2, even if I'm specifically looking for "test2:999"...

Please help.
Feb 22 '08 #1
0 820

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by aeuglein | last post: by
3 posts views Thread by Alan Pretre | last post: by
3 posts views Thread by Vidar Skjelanger | last post: by
reply views Thread by Tidane | last post: by
4 posts views Thread by pedrito | last post: by
8 posts views Thread by Tim Nash (aka TMN) | last post: by
reply views Thread by suresh191 | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.