converting RegularExpressions.GroupCollection to array of strings

  • Thread starter Thread starter Analysis&Solutions
  • Start date Start date
A

Analysis&Solutions

I have a situation where I use regular expression subpattern matches to
construct new strings. In some cases, the values need to be tweaked
before constructing the new string. In Visual Basic, the match groups
are read only:

' Property 'Value' is 'ReadOnly'.
mtch.Groups.Item(1).Value = "foo"


So I want to assign the values to a temporary array of strings. But each
way I try to do so results in error messages or warnings saying it's not
doable:

' Option Strict On disallows implicit conversions from
' 'System.Collections.Generic.IEnumerable(Of String)'
' to '1-dimensional array of String'.
Dim baz() As String = mtch.Groups.Cast(Of String)()

' Value of type 'System.Text.RegularExpressions.GroupCollection'
' cannot be converted to 'String'.
Dim foo() As String = DirectCast(mtch.Groups, String)

' Value of type 'System.Text.RegularExpressions.GroupCollection'
' cannot be converted to 'System.Array'.
Dim bar() As String = DirectCast(mtch.Groups, Array)


Is there a way to do what I want, please?

Of course, I could loop over each group element and put the value in an
array manually, but this is less than elegant. I've searched all over the
net and have had no luck.

Thanks,

--Dan
 
You can use LINQ and extension methods:

Dim xs As System.Text.RegularExpressions.GroupCollection
Dim ss() As String = (From x In xs Select (x.ToString)).ToArray
 
In said:
Dim xs As System.Text.RegularExpressions.GroupCollection
Dim ss() As String = (From x In xs Select (x.ToString)).ToArray

Works like a charm. Many thanks,

--Dan
 
Back
Top