python - 正则表达式:匹配所有内容,直到 `:` 或 `(`

标签 python regex python-3.x

我想要一个正则表达式来获取所有内容,直到第一次出现 char : 或 char (,前面有一个可选的空格。

拿这段文字:

foo : bar
foo bar: baz
foo (bar): baz

预期:

<foo>: bar
<foo bar>: baz
<foo> (bar): baz

我尝试了这个 (.*[:\(]),但是这给出了:

<foo :> bar
<foo bar:> baz
<foo (bar):> baz

参见 https://regex101.com/r/sR4hA5/1

我正在使用 Python 3.5。

有什么想法吗?

最佳答案

你可以使用

^([^:(]+?)(\s*[:(])

并替换为<\1>\2 .查看regex demo .

模式匹配:

  • ^ - 字符串开始
  • ([^:(]+?) - 第 1 组匹配除 : 以外的 1 个或多个字符和 (但尽可能少到第一个......
  • (\s*[:(]) - 第 2 组:零个或多个空格后跟 :( .

惰性量词 +?需要强制“尾随”空格落入第 2 组。

Python 3 demo :

import re
p = re.compile(r'^([^:(]+?)(\s*[:(])', re.MULTILINE)
s = "foo : bar\nfoo bar: baz\nfoo (bar): baz"
result = p.sub(r"<\1>\2", s)
print(result)

关于python - 正则表达式:匹配所有内容,直到 `:` 或 `(`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490619/

相关文章:

python - 如何查找字符串中子字符串的出现次数并将其存储到Python字典中?

python - key 错误 : "[' petal length'] not in index"

regex - Powershell RegEx 在字符串开头匹配负向后查找

用于使 TextMate 中最后一个字符大写的正则表达式语法

python - 如何修复在 python 中找不到的模块

python - 从 pandas 数据帧加载的 QTableView 中的多列过滤错误

python - 无法在 ubuntu 18.04 docker/bin/sh : 1: pip: not found 中安装 pip

python - 使用 python/elementtree 解析 xml

python - 仅在 a 元素中用于 href 的正则表达式

python - 向打开的 python 终端发送命令