繁体   English   中英

使用Python的re模块查找匹配给定模式的字符串并分隔行

[英]Finding a string matching a given pattern and separating lines using Python's re module

在一个随机字符串中,我需要找到一个匹配给定模式的字符串,然后放入; 在此字符串之后。 我认为我应该使用re来做到这一点,但是我并不那么熟悉。

输入示例:

this is the first part of string 1/32 part this is the second part of string

其结果是,我需要把; 1/32 part ,例如

this is the first part of string 1/32 part; this is the second part of string

我知道我应该使用re ,而且我知道我应该将re.match与看起来像[1-1000]/[1-1000]\\spart re.match的模式一起使用,但是我不确定从这里开始。

编辑: 1/32是一个示例,它可以是65/123 1/3 65/123 1/3 65/123 1/3 6/7

您只需要使用re模块中的re.matchre.sub以及以下正则表达式

import re

my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(\d+/\d+\s+part)'

if re.match(my_regex, my_str):
    print(re.sub(my_regex, r'\1,', my_str))  # this will print: 1/32 part,
    # ...

如果您需要多行来匹配同一个正则表达式,就需要在正则表达式中添加一些额外的标志。 请参阅此处的此类标志列表。

你可以在这里看到正则表达式


快速替换(可能会有更好的方法)是在所需的匹配零件之前和之后也进行零件匹配,并执行以下操作:

import re

my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(.*)(\s+\d+/\d+\s+part)(.*)'

condition = re.match(my_regex, my_str)

if condition:
    part = re.sub(my_regex, r'\2,', my_str)

x = condition.group(1) + part + condition.group(3)
print(x)

将输出修改后的字符串:

这是字符串的第一部分1/32部分,这是字符串的第二部分

具有以上所有功能的简单的单行函数将是:

import re


def modify_string(my_str, my_regex):
    return re.sub(my_regex, r'\1,', my_str)

if __name__ == '__main__':
    print(modify_string('first part of string 1/32 part second part of string', r'(\d+/\d+\s+part)'))

但是我建议保持这种状况。 以防万一

您的用例称为替换。 这正是re.sub函数的用途。

import re

s = "bla 1/6 part bla bla 76/88 part 12345/12345 part bla"
print(s)
s = re.sub(r'(\b\d{1,4}/\d{1,4} part)', r'\1;', s)
print(s)

这个的输出是

bla 1/6 part; bla bla 76/88 part; 12345/12345 part bla

注意遗失; 在最后出现的part

我使用{}量词将分数的分子和分母限制为4个十进制数字,这是您用[1-1000]表示法提到的。 它甚至可以更好地近似为1?\\d{1,3} (但这也不完全相同,例如还允许使用1999/1999[1]


[1] ps正如三元论者所评论的 ,十进制数从1到1000的精确正则表达式是[1-9]([0-9][0-9]?)?|1000 ,看起来有点复杂,但是如果您将唯一的4位数字1000分开,并在1至3位数字部分上使用一对多余的括号,则构建模式将变得显而易见: [1-9]([0-9]([0-9])?)? 另一种选择是对[0-9]使用字符类快捷方式\\d ,从而得到[1-9]\\d{0,2}|1000

编辑:

  • 组合了比赛分组。
  • 在分子之前添加了锚点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM