Javascript + Regex = Nothing to repeat error?

后端 未结 5 1881
既然无缘
既然无缘 2020-11-29 06:54

I\'m new to Regex and I\'m trying to work it into one of my new projects to see if I can learn it and add it to my repitoire of skills. However, I\'m hitting a roadblock her

相关标签:
5条回答
  • 2020-11-29 07:25

    Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,

    Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'
    

    So, what was the error in my case was that + operator after the / in the start of the regex. So enclosing the + operator with square brackets [+], and again sending the request, worked like a charm.

    Following will work:

    /[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/
    

    This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)

    0 讨论(0)
  • 2020-11-29 07:34

    Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:

    if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {
        // ... stuff ...
    }
    

    Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).

    0 讨论(0)
  • 2020-11-29 07:39

    You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

    The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

    "[\\[\\]?*+|{}\\\\()@.\n\r]"
    

    Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

    0 讨论(0)
  • 2020-11-29 07:44

    Firstly, in a character class [...] most characters don't need escaping - they are just literals.

    So, your regex should be:

    "[\[\]?*+|{}\\()@.\n\r]"
    

    This compiles for me.

    0 讨论(0)
  • 2020-11-29 07:47

    For Google travelers: this stupidly unhelpful error message is also presented when you make a type and double up the + regex operator:

    Okay:

    \w+
    

    Not okay:

    \w++
    
    0 讨论(0)
提交回复
热议问题