Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex to match the very precise number of the same characters

String example:

~~333~~

I need to get everything inbetween

~~

Regex that works:

/^(~{2})(.*?)(~{2})$/gm

But it also gets this string:

~~~333~~~

and also this:

~~~~333~~~~

What regex will get only the first one?

like image 577
Mary N Avatar asked Nov 26 '25 03:11

Mary N


2 Answers

The reason your regex is matching the latter two test cases is because of your wildcard character . is picking up the inner ~s. To fix this, and make it only match numbers you could do this:

/^~{2}([0-9]*)~{2}$/gm

If you want to catch other characters as well as long as they ae not ~ you could match all characters excluding the ~ character like this:

^~{2}([^~]*)~{2}$

Both of these only match the first test case ~~333~~ and not the others.

like image 62
Nasser Kessas Avatar answered Nov 27 '25 16:11

Nasser Kessas


You could use a lookaround approach on both ends to ensure that tilde does not precede or follow the ~~ markers.

var input = "~~333~~ ~~~444~~~ ~~~~5555~~~~";
var matches = input.match(/(?:^|[^~])~~([^~]+)~~(?!~)/g);
console.log(matches);
like image 31
Tim Biegeleisen Avatar answered Nov 27 '25 16:11

Tim Biegeleisen