在一个随机字符串中,我需要找到一个与给定模式匹配的字符串,并在这个字符串后面加上;
。我想我应该用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/123
,1/3
,6/7
您的用例称为替换。这正是^{} 函数的作用。你知道吗
它的输出是
注意最后一次出现
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
模块中的^{如果需要多行代码来匹配同一个正则表达式,则需要向正则表达式添加一些额外的标志。请参阅here此类标志的列表。你知道吗
您可以看到regex here
快速更换(可能有更好的方法)还可以在所需匹配零件之前和之后匹配零件,并执行以下操作:
将输出修改后的字符串:
具有上述所有功能的简单单行函数是:
但我建议保持这种状态。以防万一。你知道吗
相关问题 更多 >
编程相关推荐