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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With