如何在正则表达式中的[…]内逐字匹配“”

2024-04-19 23:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python中的正则表达式匹配[..]块中的“-”,但我不确定如何实现,因为“-”表示该块中的范围

编辑:我失败的正则表达式:

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

Tags: re编辑regexcompile
2条回答

只需将其放在[](字符类)的开头:

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

它为什么起作用?

当您将连字符放在字符类的开头时,大多数正则表达式引擎都足够智能,可以意识到您指的是文字连字符(因为您不能指示没有开头的范围)

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.

相关问题 更多 >