简体   繁体   English

如何在正则表达式中匹配' - '在[..]内部

[英]How to match '-' literally inside [..] in regular expression

I am trying to match a '-' inside a [..] block using regular expressions in python, but, I am not sure how to make that happen, since '-' denotes ranges in that block. 我试图在[...]块中使用python中的正则表达式匹配' - ',但是,我不确定如何实现这一点,因为' - '表示该块中的范围。

Edit: my failing regex: 编辑:我失败的正则表达式:

regex = re.compile("^[0-9+-*/]+$")

From the docs : 来自文档

If you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character. 如果要在集合中包含']''-' ,请在其前面加上反斜杠,或将其作为第一个字符。

Just place it at the beginning of the [] (character class): 只需将它放在[] (字符类)的开头:

regex = re.compile("^[-0-9+*/]+$")

Why does it work? 它为什么有效?

When you place the hyphen at the beginning of the character class, most regular expression engines are intelligent enough to realize that you mean a literal hyphen (since you can't indicate a range without an beginning). 当您将连字符放在字符类的开头时,大多数正则表达式引擎都足够智能,可以意识到您的意思是字面连字符(因为您无法指示没有开头的范围)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM