[英]Python regex sub part of matched string
I want to substitute 1st part of the regex matched string. 我想替换正则表达式匹配字符串的第一部分。 I am using re (regex) package in python for this: 我为此在python中使用re (regex)包:
import re
string = 'H12-H121'
sub_string = 'H12'
re.sub(sub_string,"G12",string)
>> G12-G121
Expected Output: 预期产量:
>> G12-H121
You should tell engine that you want to do matching and substitution to be done at beginning using ^
anchor: 您应该告诉引擎,您想在开始使用^
锚进行匹配和替换:
re.sub('^H12', 'G12', string)
or if you are not sure about string after -
: 还是不确定-
之后的字符串:
re.sub('^[^-]+', 'G12', string)
If you only need to replace first occurrence of H12
use parameter count
: 如果只需要替换第一次出现的H12
使用参数count
:
re.sub('H12', 'G12', string, count = 1)
^[^-]+
breakdown: ^[^-]+
细分:
^
Match start of input string ^
输入字符串的匹配开始 [^-]+
Match one or more character(s) except -
[^-]+
匹配一个或多个字符,但-
add a 1 for the count of occurrences to replace to the call to re.sub. 为要替换的出现次数添加1,以替换对re.sub的调用。 what i mean is: 我的意思是:
import re
string = 'H12-H121'
sub_string = 'H12'
re.sub(sub_string,"G12",string, 1) #<---- 1 added here
now the output is 'G12-H121'
since it only replaces the first match 现在输出为'G12-H121'
因为它仅替换了第一个匹配项
You can do this with just a str.replace()
你可以只用一个str.replace()
full_string = 'H12-H121'
sub_string = 'H12'
output_string = full_string.replace(sub_string,"G12",1)
print(output_string)
outputs: 输出:
G12-H121
Just add a ^ to the substring re pattern 只需在子字符串re模式中添加^
import re
s1 = 'H12-H121'
pat = r'^H12'
print(re.sub(pat,"G12",s1))
outputs G12-H121
输出G12-H121
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.