Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put Regex.Matches into an array?

Tags:

arrays

c#

regex

I have multiple Regex Matches. How can I put them into an array and call them each individually, for example ID[0] ID[1]?

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\",");
string ID = Regex.Matches(textt, @value);`
like image 589
user556396 Avatar asked Jan 08 '11 04:01

user556396


People also ask

Can I use regex in array?

This is possible when regex applied on this string array. But Build Regular Expression Action only can take String as a Input not a Array of Strings.

How do you match a sequence in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you check if a string matches a regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What is regex matches?

Matches(String, Int32) Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string. Matches(String) Searches the specified input string for all occurrences of a regular expression.


2 Answers

You can do that already, since MatchCollection has an int indexer that lets you access matches by index. This is perfectly valid:

MatchCollection matches = Regex.Matches(textt, @value);
Match firstMatch = matches[0];

But if you really want to put the matches into an array, you can do:

Match[] matches = Regex.Matches(textt, @value)
                       .Cast<Match>()
                       .ToArray();
like image 155
Ani Avatar answered Sep 23 '22 14:09

Ani


Or this combo of the last 2 might be a little easier to take in... A MatchCollection can be used like an array directly - no need for the secondary array:

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\",");
MatchCollection matches = Regex.Matches(textt, @value);
for (int i = 0; i < matches.Count; i++)
{
    Response.Write(matches[i].ToString());
}
like image 40
vapcguy Avatar answered Sep 23 '22 14:09

vapcguy