python - 定位和可选组

标签 python regex

我的示例数据集:

Loaded: mismatch (No such file or directory)
Loaded: not-found ()
Loaded: error (Reason:No such file or directory)
Loaded: error (Reason: No such file or directory)
Loaded: mystery

我的正则表达式测试(逐行读取):

re.findall("[Loaded: ](\S*) \([Reason: ]?(.*)\)", line)

我分别得到:

[('mismatch', 'No such file or directory')]
[('not-found', '')]
[('error', 'eason:No such file or directory')]
[('error', 'eason: No such file or directory')]

第一个和第二个列表都可以。

但是第三个和第四个不是,并且缺少第五个。

如何解决这个问题?

最佳答案

不确定这是否是您需要的,但它符合所有
你的测试字符串正确。

组 1 是加载的消息,组 2 是原因。

 # Loaded:\s+(\S+)(?:\s+\((?:Reason:\s*)?([^)]*)\))?     

 Loaded: \s+ 
 ( \S+ )                  # (1)
 (?:
      \s+ 
      \( 
      (?: Reason: \s* )?
      ( [^)]* )                # (2)
      \) 
 )?

关于python - 定位和可选组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28838236/

相关文章:

java - 为什么 java-regex\d 匹配下划线?我该如何解决?

Python 正则表达式被方括号 ([]) 混淆了?

python - 为什么 re.escape 逃脱空间

python - 从库返回的 ctypes 结构

python random.sample ("abc",3) 。如何使用正则表达式代替 "abc"

javascript - 正则表达式 - 从字符串中删除运算符的替换方法会产生不需要的结果

c# - 正则表达式获取最后检测到的字符串之后的所有行

python - 如何在cx_freeze中包含一个文件夹?

python - 使用 Python 时如何在 Google Colab 中引用文件?

Python 等式检查差异