tags:

views:

36

answers:

2

Can someone explain this to me. I am pretty good with perl regular expressions but evidently I am at a loss on why this doesn't work.

The code below stores "Person Test" in output variable.

im output As String
Dim userName As String = "Test, Person"
Dim re As New Regex("(\w+),\s(\w+)", RegexOptions.Singleline)
output = re.Replace(userName, "$2 $1")

So why doesn't the following code store "#Test##Person#" in output variable.

Dim output As String
Dim userName As String = "Test, Person"
Dim re As New Regex("(\w+),\s(\w+)")
For Each Match As Match In re.Matches(userName)
    output &= "#" & Match.ToString & "#"
Next

Thanks for the help.

A: 

I think this will work

output = re.Replace(userName, "\2 \1")

For second:

For Each Match As Match In re.Matches(userName)
    output &= "#" & Match.Groups(1) & "#" & "#" & Match.Groups(2) & "#"
Next
Andrey
+2  A: 

You are confusing matches and groups. A match is the entire match, including all characters both in groups and not in groups. A group is only the part of the match in parentheses. In .NET group 0 is the entire match, and the remaining groups 1,2,... etc are similar to how $1, $2 etc... work in Perl. You might understand it better if you try running this:

    For Each Group As Group In re.Match(userName).Groups
        output &= "#" & Group.ToString & "#"
    Next
Mark Byers
Thank you. I knew there was something simple I was missing.
Threekill