-2

I have a string, and I need to remove a substring from the string. The substring is enclosed in identifiers (e.x [[1]] substring [[\1]]).

String e.x: [[1]] abc [[\1]] [[2]] pqr [[\2]] xyz [[3]] rst [[\3]] [[5]] ijk [[\5]]

I expect to get [[1]] abc [[\1]] from string:

[[1]] abc [[\1]] [[2]] pqr [[\2]] xyz [[3]] rst [[\3]] [[5]] ijk [[\5]]

if I know the substring abc

I have tried this solution: /\[\[(\d)\]\] pqr \[\[\\\1\]\]/gm but I need to provide dynamic text.

(e.x if I want to remove abc, i need to find the text enclosed in the identifiers in the string and remove it)

1 Answers1

1

Backslashes in your string need to be escaped otherwise they will be interpreted wrong. \d matches a digit, characters such as [ in regex need to be escaped because they are used for special purposes when not escaped.

var string = "[[1]] abc [[\\1]] [[2]] pqr [[\\2]] xyz [[3]] rst [[\\3]] [[5]] ijk [[\\5]]";
var substr = "abc";
regex = new RegExp("(\\[\\[\\d]] "+substr+" \\[\\[.\\d]])");
string.match(regex)[1]; // [[1]] abc [[\1]]
JEL
  • 208
  • 1
  • 5
  • Hi, New requirement: If a number is already used, it cannot be used in another identifier, for ex: if 1 is used already, it can not be used in another identifier. Is this possible inside the regex?? – Roshan Suvarna Sep 09 '19 at 09:51
  • Please need your help – Roshan Suvarna Sep 09 '19 at 12:39
  • I don't know how that would be done with regex, but it may be possible. [This question](https://stackoverflow.com/questions/32375217/regular-expression-ignore-duplicate-matches) may be similar or possibly another question? You might want to try making a loop through the matches and discarding/flagging ones that include a number you've seen before (add numbers you've seen to an array)? I'd recommend trying things out, looking at related questions, and if it's not working you could create a new question. – JEL Sep 10 '19 at 10:26