jCu*_*uga 13 python regex string replace
假设我有一个包含大量随机内容的字符串,如下所示:
strJunk ="asdf2adsf29Value=five&lakl23ljk43asdldl"
Run Code Online (Sandbox Code Playgroud)
而且我有兴趣获得位于'Value ='和'&'之间的子串,在这个例子中它将是'5'.
我可以使用如下的正则表达式:
match = re.search(r'Value=?([^&>]+)', strJunk)
>>> print match.group(0)
Value=five
>>> print match.group(1)
five
Run Code Online (Sandbox Code Playgroud)
为什么match.group(0)是整个'Value = five'而group(1)只是'five'?我有办法让'五'成为唯一的结果吗?(这个问题源于我对正则表达式的一种微弱的把握)
我也将不得不在这个字符串中进行替换,如下所示:
val1 = match.group(1)
strJunk.replace(val1, "six", 1)
Run Code Online (Sandbox Code Playgroud)
产量:
'asdf2adsf29Value=six&lakl23ljk43asdldl'
Run Code Online (Sandbox Code Playgroud)
考虑到我计划一遍又一遍地执行上述两个任务(在'Value ='和'&'之间找到字符串,以及替换该值),我想知道是否还有其他更有效的方法来寻找substring并在原始字符串中替换它.我很好地坚持我所拥有的,但我只是想确保如果有更好的方法,我不会花费更多的时间.
命名组使得之后更容易获得组内容.编译正则表达式一次,然后重用编译对象,将比为每次使用重新编译它更有效(这是重复调用re.search时会发生的情况).您可以使用正向lookbehind和lookahead断言来使此正则表达式适合您要执行的替换.
>>> value_regex = re.compile("(?<=Value=)(?P<value>.*?)(?=&)")
>>> match = value_regex.search(strJunk)
>>> match.group('value')
'five'
>>> value_regex.sub("six", strJunk)
'asdf2adsf29Value=six&lakl23ljk43asdldl'
Run Code Online (Sandbox Code Playgroud)