Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for odd numbers of backslashes in a regex using Javascript?

I have recently asked a question regarding an error I have been getting using a RegExp constructor in Javascript with lookbehind assertion.

What I want to do it, to check for a number input bigger than 5 preceded by an odd number of backslash, in other words, that is not preceded by an escaped backslash

Here is an example.

\5              // match !
\\5            // no match !
\\\5           // match!

The Regex I found online is

(?<!\\)(?:\\{2})*\\(?!\\)([5-9]|[1-9]\d)

But the problem here is that (?<!\\) causes a problem with javascript throwing an error invalid regex group.

Is there a workaround for this ?

Finally, I know that my current regex also may have an error regarding the detection of a number larger than 5, for example \55 will not match. I would appreciate your help.

thank you

like image 318
Ziko Avatar asked Oct 18 '25 16:10

Ziko


1 Answers

JS doesn't support lookbehinds (at least not all major browsers do), hence the error. You could try:

(?:^|[^\\\n])\\(?:\\{2})*(?![0-4]\b)\d+

Or if you care about decimal numbers:

(?:^|[^\\\n])\\(?:\\{2})*(?![0-4](?:\.\d*)?\b)\d+(?:\.\d*)?

Live demo

Note: You don't need \n if you don't have multi line text.

Regex breakdown:

  • (?: Beginning of non-capturing group
    • ^ Start of line
    • | Or
    • [^\\\n] Match nothing but a backslash
  • ) End of non-capturing group
  • \\(?:\\{2})* Match a backslash following even number of it
  • (?![0-4](?:\.\d*)?\b) Following number shouldn't be less than 5 (care about decimal numbers)
  • \d+(?:\.\d*)? Match a number

JS code:

var str = `\\5
\\\\5
\\\\\\5
\\\\\\4
\\4.
\\\\\\6
`;

console.log(
  str.match(/(?:^|[^\\\n])\\(?:\\{2})*(?![0-4](?:\.\d*)?\b)\d+(?:\.\d*)?/gm)
)
like image 191
revo Avatar answered Oct 20 '25 04:10

revo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!