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

浪尽此生 提交于 2019-12-11 15:39:42

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/50334881/how-to-check-for-odd-numbers-of-backslashes-in-a-regex-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!