abc cba
abc cba

Reputation: 2633

Regular expression Invert within Match

My string as follow

Data['5']=new Array('Jame', '54', '22', 'Dis')

My regex are as follow (Data\[.+\]) will return me Data['5'] , I understand that I can use the regex (\d+) and filter again to get the 5 , but by doing that it incur of two time of use regular expression which I think is not a a good approach , and I am using C#.

Is that anyway that I could all combine the (Data\[.+\]) and (\d+) , or any regex combination that allow me to get the number value inside the data like Data['5']=new Array('Jame', '54', '22', 'Dis') will return me a 5 .

Upvotes: 0

Views: 454

Answers (4)

gpmurthy
gpmurthy

Reputation: 2427

Consider the following Regex...

(?<=Data\[\')\d+

Upvotes: 0

Marius Schulz
Marius Schulz

Reputation: 16440

You can simply use the following pattern: Data\['([0-9]+)'\]. Your first match will then contain the number you're looking for.

As you said, there's no need to perform two matches. With the above pattern, you're not looking for any sequence of characters within the brackets (.+), but for digits only (\d+).

Upvotes: 0

AnkurTG
AnkurTG

Reputation: 21

I suppose you can use a look-behind, which is supported in C# Regex, if I remember right.

Your regex would be like:

(?<=(Data\['))\d+

This should pick out rows you want, and return only the number inside the square brackets.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236238

Use Data\['(\d+)'\].* pattern to capture group with index of data:

var s = "Data['5']=new Array('Jame', '54', '22', 'Dis')";
var match = Regex.Match(s, @"Data\['(\d+)'\].*");
var index = match.Groups[1].Value; // 5

Upvotes: 1

Related Questions