简体   繁体   中英

Regular Expression to replace part of a string

I need to replace part of a string, it's dynamically generated so I'm never going to know what the string is.

Here's an example "session12_2" I need to replace the 2 at the end with a variable. The "session" text will always be the same but the number will change.

I've tried a standard replace but that didn't work (I didn't think it would).

Here's what I tried:

col1 = col1.replace('_'+oldnumber+'"', '_'+rowparts[2]+'"');

Edit: I'm looking for a reg ex that will replace '_'+oldnumber when it's found as part of a string.

If you will always have the "_" (underscore) as a divider you can do this:

 str = str.split("_")[0]+"_"+rowparts[x];

This way you split the string using the underscore and then complete it with what you like, no regex needed.

var re = /session(\d+)_(\d+)/; 
var str = 'session12_2';
var subst = 'session$1_'+rowparts[2]; 

var result = str.replace(re, subst);

Test: https://regex101.com/r/sH8gK8/1

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