abusemind
abusemind

Reputation: 213

.NET regular expression find the number and group the number

I have a question about .NET regular expressions.

Now I have several strings in a list, there may be a number in the string, and the rest part of string is same, just like

string[] strings = {"var1", "var2", "var3", "array[0]", "array[1]", "array[2]"}

I want the result is {"var$i" , "array[$i]"}, and I have a record of the number which record the number matched, like a dictionary

var$i {1,2,3} & 
array[$i] {0, 1 ,2}

I defined a regex like this

var numberReg = new Regex(@".*(<number>\d+).*");
foreach(string str in strings){
  var matchResult = numberReg.Match(name);
  if(matchResult.success){
    var number = matchResult.Groups["number"].ToString();
    //blablabla

But the regex here seems to be not work(never match success), I am new at regex, and I want to solve this problem ASAP.

Upvotes: 0

Views: 359

Answers (2)

David Elizondo
David Elizondo

Reputation: 1153

It is not clear to me what exactly you want. However looking into your code, I assume you have to somehow extract the numbers (and maybe variable names) from your list of values. Try this:

// values
string[] myStrings = { "var1", "var2", "var3", "array[0]", "array[1]", "array[2]" };

// matches
Regex x = new Regex(@"(?<pre>\w*)(?<number>\d+)(?<post>\w*)");
MatchCollection matches = x.Matches(String.Join(",", myStrings));

// get the numbers
foreach (Match m in matches)
{
    string number = m.Groups["number"].Value;                
    ...
}

Upvotes: 1

Jeremy Stein
Jeremy Stein

Reputation: 19661

Try this as your regex:

(?<number>\d+)

Upvotes: 1

Related Questions