不能用正则表达式逃避反斜杠? [英] Can't escape the backslash with regex?
问题描述
我正在使用以下正则表达式
I'm using the following regex
^[a-zA-Z0-9\',!;\?\$\^:\\\/`\|~&\" @#%\*\{}\(\)_\+\.\s=-]{1,1000}$
我知道它很丑,但到目前为止,它除了不允许使用反斜杠之外还有其他用途,因为我认为它应该是因为它被转义了,我还尝试了 \\
而不是 \\\
但结果相同.有什么想法吗?
I know it's ugly, but so far it serves its purpose other than the backslash not being allowed as I think it should because it's escaped, I also tried \\
instead of \\\
but same results. Any ideas?
推荐答案
如果您将它放在程序中的字符串中,您实际上可能需要使用四个反斜杠(因为字符串解析器会在为 string 转义"它,然后正则表达式需要两个来转义正则表达式反斜杠).
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).
例如:
regex("\\\\")
被解释为...
regex("\\" [escaped backslash] followed by "\\" [escaped backslash])
被解释为...
regex(\\)
被解释为匹配单个反斜杠的正则表达式.
is interpreted as a regex that matches a single backslash.
根据语言的不同,您可能可以使用不解析转义序列的不同形式的引用以避免必须使用尽可能多的引用 - 例如,在 Python 中:
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'\\')
引号前面的 r
使它成为一个 raw 字符串,它不解析反斜杠转义.
The r
in front of the quotes makes it a raw string which doesn't parse backslash escapes.
这篇关于不能用正则表达式逃避反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!