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

2024-10-05 22:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个随机字符串中,我需要找到一个与给定模式匹配的字符串,并在这个字符串后面加上;。我想我应该用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的模式,但我不知道从这里该怎么办。你知道吗

编辑:1/32是一个例子,它可以是65/1231/36/7


Tags: ofthe字符串re编辑示例stringis
2条回答

您的用例称为替换。这正是^{}函数的作用。你知道吗

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之后缺少的;。你知道吗

我用^{} quantifiers将分数的分子和分母限制为4位小数,这是你提到的[1-1000]符号。它甚至可以用1?\d{1,3}来更好地近似(但这也不完全相同,它还允许例如1999/1999[1]。你知道吗


[1]p.s.作为tripleee commented,从1到1000的十进制数的精确正则表达式是[1-9]([0-9][0-9]?)?|1000,它看起来有点复杂,但是如果您将仅有的4位数字1000分开,并在1到3位部分使用多余的一对括号:[1-9]([0-9]([0-9])?)?,构建模式就会变得很明显。另一种选择是使用字符类快捷方式\d[0-9],结果是[1-9]\d{0,2}|1000。你知道吗

编辑:

  • 组合匹配分组。你知道吗
  • 在分子前加了锚。你知道吗

您只需使用re模块中的^{}^{},以及下面的正则表达式

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,
    # ...

如果需要多行代码来匹配同一个正则表达式,则需要向正则表达式添加一些额外的标志。请参阅here此类标志的列表。你知道吗

您可以看到regex here


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

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)

将输出修改后的字符串:

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

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

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)'))

但我建议保持这种状态。以防万一。你知道吗

相关问题 更多 >