regular expressions

  • Thread starter Thread starter steve
  • Start date Start date
S

steve

is there a way to quickly tell what portion of a regular expression matched
a string?

ex. ([a-z]{3})|(0-9{2})

if the string is "abc", i'd like to know the that the first parenth matched.
if the string is "18", i'd like to know that the second parent matched.

i'd like to avoid having to test each individual parenth pattern. i know you
can replace using $1, $2, etc. but i don't know of a similar match
interface. i also want to avoid having to name each parenth pattern.

tia,

steve
 
I believe the Groups collection of the Match object could have what you are
looking for. If you don't want to name the groups, then you can just refer
to them by number:

Dim m As Match

m = Regex.Match("abc", "([a-z]{3})|([0-9]{2})")
Console.WriteLine("Group 1: " & m.Groups(1).Value) ' -> "abc"
Console.WriteLine("Group 2: " & m.Groups(2).Value) ' -> ""

m = Regex.Match("18", "([a-z]{3})|([0-9]{2})")
Console.WriteLine("Group 1: " & m.Groups(1).Value) ' -> ""
Console.WriteLine("Group 2: " & m.Groups(2).Value) ' -> "18"


Note also that the second part of your original expression should be
changed to [0-9]{2} or \d{2} to match 2 digits.


Brian Davis
www.knowdotnet.com
 
thanks for the info...i'll try it out. trying to come up w/ dynamic data
validation. the input of one control sets the "correct" answer for
another...basically, conditional validity.

btw, that was a dummy example w/ quick typing...but thanks for the heads up
on syntax anyway.

thx again,

steve

Brian Davis said:
I believe the Groups collection of the Match object could have what you are
looking for. If you don't want to name the groups, then you can just refer
to them by number:

Dim m As Match

m = Regex.Match("abc", "([a-z]{3})|([0-9]{2})")
Console.WriteLine("Group 1: " & m.Groups(1).Value) ' -> "abc"
Console.WriteLine("Group 2: " & m.Groups(2).Value) ' -> ""

m = Regex.Match("18", "([a-z]{3})|([0-9]{2})")
Console.WriteLine("Group 1: " & m.Groups(1).Value) ' -> ""
Console.WriteLine("Group 2: " & m.Groups(2).Value) ' -> "18"


Note also that the second part of your original expression should be
changed to [0-9]{2} or \d{2} to match 2 digits.


Brian Davis
www.knowdotnet.com



steve said:
is there a way to quickly tell what portion of a regular expression matched
a string?

ex. ([a-z]{3})|(0-9{2})

if the string is "abc", i'd like to know the that the first parenth matched.
if the string is "18", i'd like to know that the second parent matched.

i'd like to avoid having to test each individual parenth pattern. i know you
can replace using $1, $2, etc. but i don't know of a similar match
interface. i also want to avoid having to name each parenth pattern.

tia,

steve
 
Back
Top