How can I replace/split a dynamic string using regular expression?

142 views Asked by At

Suppose i get dynamic string as below.

#04215: ["#02080=#04217+#04217_DUP5554","#01066=(#01047+#01111+#01048+#01118+#01049+#01050+#01121+#01128+#01131+#01141+#01138+#01148+#01053+#01062+#01054+#02080+#02048+#01064+#01063+#01065+#01051+#01052+#02062+#02069+#02072+#02079)","#02002=#01066","#02007=(#02002+#02003+#02004+#02005+#02006)","#02010=(#02007+#02008+#02009)","#04216+#04216_DUP5554=#04217+#04217_DUP5554","#04215+#04215_DUP5554=#04216+#04216_DUP5554"]

I have to make the part "#04215+#04215_DUP5554=#04216+#04216_DUP5554"] as "#04215_DUP9262=#04216+#04216_DUP9262". I made a regex to match '#04215+#04215_DUP9262=' as '([#][0]["+pgNo+"][0-9]{3}[+][#][0]["+pgNo+"][0-9]{3}[_][D][U][P][0-9]{4}[=])'. I tried the below.

Consider I get dynamic string in variable a;

var regex2=new RegExp("([#][0]["+pgNo+"][0-9]{3}[+][#][0]["+pgNo+"][0-9]{3}[_][D][U][P][0-9]{4}[=]) ([#][0]["+pgNo+"][0-9]{3}[_][D][U][P][0-9]{4})" ,"g");

a=a.replace(regex2,'$1,$2');

It is not replacing the string.Please help.

The pgNo in regex2 is dynamic. In current context, value of it is '4'. Substring is not possible because there are too many '=' symbols. Essentially, I have to change occurence of things like '#04215+#04215_DUP9262=' to '#04215_DUP9262='

1

There are 1 answers

2
scagood On

You could do something like this: /#([0-9]{5})\+#\1/g => $1.

In a code example this would be:

let regex = new RegExp('(#' + pgNo + ')\\+\\1', 'g');
let myString = "#04215+#04215_DUP9262=#04216+#04216_DUP9262";

myString = myString.replace(regex, '$1');

In this (#[0-9]{5}) will match any 5 character number after a hash, \+ matches the '+' between the numbers, (it has to be escaped otherwise it's interpreted as 'one or more' of the preceding token), and \1 is a back reference to the first match.