[英]Using re.sub() to replace some part of a string
I'm trying to use re
to replace some value in a string. 我正在尝试使用
re
替换字符串中的某些值。 Essentially, replace the first detected int (in a specific pattern ) with 1 . 本质上,将第一个检测到的int (以特定模式 )替换为1 。
Examples: 例子:
{1} -> {1}
{2} -> {1}
{3,} -> {1,}
{3,16} -> {1,16}
ab{3,16} -> ab{1,16}
5a4b{3,16} -> 5a4b{1,16}
{1,4} -> {1,4}
import re
pattern = '.*{(\d+)}|{(\d+),}|{(\d+),\d+}'
string = 'ab{3,16}'
print re.sub(pattern, '1', string)
But I get ab1
instead of ab{1,16}
但是我得到
ab1
而不是ab{1,16}
You don't want to replace the {}
or ,
, so you could use positive lookaheads and lookbehinds in order to make sure the int is : 您不想替换
{}
或,
因此可以使用正向前行和后向行来确保int为:
{
with : (?<={)
{
加上: (?<={)
}
or a ,
with : (?=}|,)
}
或a之前,
并带有: (?=}|,)
If you want to want to replace only the first occurence in the whole string, you can set the 4th argument of sub
to 1. In that case, {3}{3}
will be converted to {1}{3}
. 如果只想替换整个字符串中的第一个匹配项,则可以将
sub
的第4个参数设置为1。在这种情况下, {3}{3}
将转换为{1}{3}
。 UPDATE : You don't want it. 更新:您不想要它。 :)
:)
import re
pattern = '(?<={)\d+(?=}|,)'
string = 'ab{3,16}'
print re.sub(pattern, '1', string)
Here are some tests : 这是一些测试:
import re
def replace_first_int(string):
pattern = '(?<={)\d+(?=}|,)'
return re.sub(pattern, '1', string)
print replace_first_int('{1}')
# {1}
print replace_first_int('{2}')
# {1}
print replace_first_int('{3,}')
# {1,}
print replace_first_int('{3')
# {3
print replace_first_int('{3,16}')
# {1,16}
print replace_first_int('{1,4}')
# {1,4}
print replace_first_int('{3}{3}')
# {1}{1}
print replace_first_int('ab5')
# ab5
print replace_first_int('5a4b{3,16}')
# 5a4b{1,16}
When doing a replace with regex the whole matched string will be replaced. 当使用正则表达式进行替换时,整个匹配的字符串将被替换。 As you match the whole
{1,16}
, it is replaced by 1
accordingly. 当您匹配整个
{1,16}
,它将相应地替换为1
。
For your samples (?<=\\{)\\d+
will work as pattern and can then replaced by 1
, like 对于您的样本
(?<=\\{)\\d+
将作为模式,然后可以替换为1
,例如
import re
pattern = '(?<={)\d+'
string = 'ab{3,16}'
print re.sub(pattern, '1', string)
如果您的模式始终采用指定的格式(如您的示例中所示),那么就足够了:
print re.sub(r'{\d+', '{1', string, count=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.