Find in text all matching regex patterns from array

Do you need to search multiple regex patterns in a text to get array of all occurences?
You may find usefull following code.

patterns As String() = {"Apple\d*","Orange\d*","Banana\d*"} 
text = "Apple0001Potato005Apple0014//Banana0022" 
results As String() = patterns.Select(Function(x) New Regex(x).Matches(text).Cast(Of Match).Select(Function(y) y.Value)).SelectMany(Function(z) z).ToArray()

Result:
Apple0001
Apple0014
Banana0022

And an explanation of how it works:
1/ patterns.Select(Function(x) - take every regex “pattern” from the array
2/ New Regex(x).Matches(text) - search the “pattern” in “text” string using regex
3/ Cast(Of Match).Select(Function(y) y.Value)) - take all found matching values
4/ .SelectMany(Function(z) z).ToArray() - and flatten found results into an array

Cheers

2 Likes

For reference to the implementation have a look here:

1 Like