[英]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+-*/]+$")
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.