Can't escape the backslash with regex?

前端 未结 6 789
别那么骄傲
别那么骄傲 2020-11-22 09:04

I\'m using the following regex

^[a-zA-Z0-9\\\',!;\\?\\$\\^:\\\\\\/`\\|~&\\\" @#%\\*\\{}\\(\\)_\\+\\.\\s=-]{1,1000}$

I know it\'s ugly,

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:45

    If you're putting this in a string within a program, you may actually need to use four backslashes (because the string parser will remove two of them when "de-escaping" it for the string, and then the regex needs two for an escaped regex backslash).

    For instance:

    regex("\\\\")
    

    is interpreted as...

    regex("\\" [escaped backslash] followed by "\\" [escaped backslash])
    

    is interpreted as...

    regex(\\)
    

    is interpreted as a regex that matches a single backslash.


    Depending on the language, you might be able to use a different form of quoting that doesn't parse escape sequences to avoid having to use as many - for instance, in Python:

    re.compile(r'\\')
    

    The r in front of the quotes makes it a raw string which doesn't parse backslash escapes.

提交回复
热议问题