【问题标题】:Regular Expression : Use last matched optional capture group正则表达式:使用最后匹配的可选捕获组
【发布时间】:2017-03-28 07:01:14
【问题描述】:

我想使用正则表达式完成以下操作:

输入

M1  hello world 1234_5678  ip som lorem  9321_1231  iste natus error sit voluptatem   4313_4351  ratione voluptatem sequi nesciunt   4312_1234
M2 magnam aliquam 4351_3143  sed quia non numquam  3123_1432

输出

M1    hello world   1234    5678 
M1    ip som lorem   9321    1231
M1    iste natus error sit voluptatem   4313    4351 
M2    magnam aliquam     4351    3143 
M2    sed quia non numquam    3123    1432

正则表达式匹配

(M[1|2])?\s+(\D+)(\d{4})_(\d{4})(\n)?

和子

\1\t\2\t\3\t\4\n

让我靠近(见:https://regex101.com/r/tKgCBi/1/

M1  hello world     1234    5678
    ip som lorem    9321    1231
    iste natus error sit voluptatem     4313    4351
    ratione voluptatem sequi nesciunt       4312    1234

M2  magnam aliquam  4351    3143
    sed quia non numquam    3123    1432

如果没有进行此(可选)匹配,我如何使用最后一个(可选)匹配组?我假设它在(M [1 | 2])时设置\ 1 = NULL?失败。

(我正在使用 Python 的“re”模块)

【问题讨论】:

  • 这里真正的问题是什么?您的`“让我靠近”和“当没有进行此(可选)匹配时,我如何使用最后一个(可选)匹配组?我假设它在(M [1 | 2])时设置\ 1 = NULL?失败。”没有帮助。
  • 我不确定你的意思。我可以提供什么说明?
  • 我正在使用 python 的“re”模块。 (可能应该提到这一点。我编辑了我的帖子。)
  • 我的意思是 (M[1|2])? 不是 last 组。你得到的结果到底有什么问题?
  • 你可以这样做 - ideone.com/gmUYDS(也许)。

标签: regex capture-group


【解决方案1】:

您可以使用 2-regex 方法:匹配符合拆分条件的行,然后将这些匹配传递给回调方法以进一步处理它们:

import re

s = '''M1  hello world 1234_5678  ip som lorem  9321_1231  iste natus error sit voluptatem   4313_4351  ratione voluptatem sequi nesciunt   4312_1234
M2 magnam aliquam 4351_3143  sed quia non numquam  3123_1432'''

def repl(m):
    return re.sub(r'\s+(\D+)(\d{4})_(\d{4})', '{}\t\\1\t\\2\t\\3\n'.format(m.group(1)), m.group(2))

whole_line_pattern = r'(?m)^(M[12])?((?:\s+\D+\d{4}_\d{4})+)$[\n\r]*'
res = re.sub(whole_line_pattern, repl, s)
print(res)

online Python demo

模式 1

  • (?m)^ - 匹配行首
  • (M[12])? - 组 1 匹配 M1M2
  • ((?:\s+\D+\d{4}_\d{4})+) - 1 个或多个序列:
    • \s+ - 1+ 个空格
    • \D+ - 1+ 非数字字符
    • \d{4}_\d{4} - 4 位,_,4 位
  • $[\n\r]* - 行尾有 0+ 个换行符

每个匹配都使用repl 方法处理。正则表达式替换发现

  • \s+ - 1+ 个空格
  • (\D+) - 第 1 组:一个或多个非数字字符
  • (\d{4}) - 第 2 组:四位字符
  • _ - _ 符号
  • (\d{4}) - 第 2 组:四位字符

匹配替换为M1M2m.group(1)),\\1等是对插入非数字块和用制表符括起来的4位块的捕获组的反向引用.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 2020-06-24
    相关资源
    最近更新 更多