python - Python RE匹配不是左括号然后是字符串
问题描述
我想使用 python 匹配以下模式re.search
:
((不是左括号,然后是 1-3 个空格)或(字符串的开头))然后是(字符 1 或 E)然后是(任意数量的空格)然后是(右括号)。
这是我到目前为止所拥有的:
re.search(r'((^\(\s{1,3})|^)[1tE]\s+\)', text)
想匹配例子
text = " E )"
text = "1 )"
不想匹配示例
text = "( 1 )
解决方案
考虑以下模式:
(
( not open bracket, then 1-3 spaces)
-[^(]\s{1,3}
or
-|
(the start of the string)
-^
)
(characters 1 or E)
-[1E]
(any number of spaces)
-\s*
(close bracket)
-\)
。
将所有这些加入一个模式:
(?:[^(]\s{1,3}|^)[1E]\s*\)
要匹配整个字符串,请添加锚点,^
然后$
:
^(?:[^(]\s{1,3}|^)[1E]\s*\)$
请参阅正则表达式演示。
这(?:...)
是一个非捕获组,如果您将来需要访问它的值,请使用捕获组。
您可以使用详细的正则表达式表示法使其更具可读性和可维护性:
re.search(
r"""
(?:
[^(]\s{1,3} # not open bracket, then 1-3 spaces
| # or
^ # the start of the string
)
[1E] # characters 1 or E
\s* # any number of spaces
\) # close bracket
""",
text,
re.VERBOSE
)
推荐阅读
- python - 多个 if 条件给了我错误的答案
- spring-boot - 当我想我尝试了很多解决方案时,如何在 Kotlin 和 Gradle 项目中使用 DevTools?
- python - 为什么 tf.matmul 不能与转置张量一起使用?
- css - 如何在详细信息上方设置 Woocommerce 产品图片
- excel - 根据多个单元格值隐藏或取消隐藏工作表
- python - 无法在scrapy的解析回调中发送请求
- python - 过大的预测 MLPRegressor
- python-3.x - 如何打开已编译的 Python 文件 (.pyc)
- ios - css 媒体查询不适用于 ipad 横向模式
- syntax - 尝试定义内部函数时出现语法错误