Michael D. Kirkpatrick
Michael D. Kirkpatrick

Reputation: 488

Regex help to extract value from string

I can't figure out how to extract specific numbers with a specific match from a string.

Example:

string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");

Apparently the regex is sound.

Match myMatch = myIDsReg.Match(myString);

Yields "**[10]**" but nothing else.

I can't figure out how to get an array with the following values: 10, 20, 30

Upvotes: 2

Views: 190

Answers (3)

Michael D. Kirkpatrick
Michael D. Kirkpatrick

Reputation: 488

Trikks came up with the best answer. I just had to modify it a little to work best for me.

string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");
string[] regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToArray();

I basically replaced "select match.Value" with "select match.Groups[1].Value".

Thanks for your help!

Upvotes: 1

Eric Herlitz
Eric Herlitz

Reputation: 26307

I would do this

string myString = "blah blah **[10]** blah **[20]** and some more blah **[30]**";
Regex myIDsReg = new Regex(@"\*\*\[(\d+)\]\*\*");
string[] regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToArray();

You can select which output you want as well

List<string> regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value).ToList();

or

IEnumerable<string> regexResult = (from Match match in myIDsReg.Matches(myString) select match.Groups[1].Value);

I'd prefer one of the two latter

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839254

Use Matches instead of Match.

foreach (Match match in myIDsReg.Matches(myString))
{
    // etc...
}

See it working online: ideone

Upvotes: 4

Related Questions