简体   繁体   中英

Matching the first occurrence of underscore followed by a digit and replacing set of matches in html

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?

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 .

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

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\])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM