简体   繁体   English

python获取正则表达式匹配的字符串部分

[英]python get the part of the string matched by the regex

In the case of re.search() , is there a way I can get hold of just the part of input string that matches the regex? re.search()的情况下,有什么办法可以让我只保留与正则表达式匹配的输入字符串的一部分? ie I just want the "heeehe" part and not the stuff that comes before it: 即我只想要"heeehe"部分,而不想要它"heeehe"的东西:

>>> s = "i got away with it, heeehe"
>>> import re
>>> match = re.search("he*he", s)
>>> match.string
'i got away with it, heeehe'
>>> match.?
'heeehe'

match.group(0) is the matched string. match.group(0)是匹配的字符串。

Demo: 演示:

>>> import re
>>> s = "i got away with it, heeehe"
>>> match = re.search("he*he", s)
>>> match.group(0)
'heeehe'

You can also omit the argument, 0 is the default. 您也可以省略参数,默认0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM