Home > database >  JavaScript regex to match the very precise number of the same characters
JavaScript regex to match the very precise number of the same characters

Time:12-30

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?

CodePudding user response:

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.

CodePudding user response:

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);

CodePudding user response:

To get the string between the first set of double tildes (~~) and exclude strings with additional tildes, you can use the following regular expression:

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

([^~]*): This matches zero or more characters that are not tildes ([^~]). The * specifies that the preceding character or group (in this case, the negated character class) should be matched zero or more times.

CodePudding user response:

The below regex will match for exact two '~' in beginning and at last. And any string between those.

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

CodePudding user response:

Try this:

^~~[^~\r\n] ~~$

^ match the start of the line.

~~ match two literal ~.

[^~\r\n] match one or more character that is not ~ because we don't want to cross the two closing ~~, and also not \r or \n because we also don't want to cross newline characters.

~~ match two literal ~.

$ match the end of the line.

See regex demo.

  • Related