2

I have the following strings:

foo_0_13
foz[0][bar][]
far_0

I have a convention, and need to match from strings like foo_0_13 and far_2 the underscore and the digit following, example _0 or _2... And for any string with structure foz[0][bar][] or foz[3] I need to match [0] or [3]

I have tried ((\_\d)|\[\d\]) but this matched _0_1, how can I make it match only _0?

I need to find only the first occurrence of the "underscore-digit" combination.

Second part:

If I have an html division with multiple occurrence of _0 and [0] as

<div id="foo_0_13" name="bar[0][xxx][]"> <p id="par_0">Test</p> </div>

and I need to replace all the these occurrence with _1 so that the html becomes

<div id="foo_1_13" name="bar[1][xxx][]"> <p id="par_1">Test</p> </div>

how can I elaborate this to get the desired html knowing that am using javascript?

KAD
  • 10,972
  • 4
  • 31
  • 73

3 Answers3

2

You can try the following regex replace.

var res = str.replace(/("[a-z]+[_[])\d+/g, '$01' + '1'); // 1 = new digit

See regex demo at regex101 or js fiddle

In the replacement I used '$01' + '1' just to visualy separate the backreference group 1 from the newly added digit. Acutally the replacement would be $11 or $011 where the last to be preferred.

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46
1

Start at the beginning of your string. Match everything ungreedily in a non-capturing group until you encounter either of the patterns to match.

(?:^.*?)(_\d|\[\d\])

Demo and breakdown: https://regex101.com/r/cT6qX2/1

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

If you are using an implementation that is pulling groups you can isolate the possible second underscore and digit outside of the group.

Without knowing the regex implementation or language it's hard to give a perfect answer.

Example:

(_\d)_*|(\[\d\])
Nick Burns
  • 192
  • 4
  • This seems good but I have to capture 2 groups rather than 1, I think @timgeb s approach is better. As for the language, I am using javascript – KAD Feb 21 '16 at 19:33
  • I like @timgeb s approach as well but note that it is one capturing group, some combination of the two seems in order – Nick Burns Feb 21 '16 at 19:37