Python:获取正则表达式匹配的文本

时间:2022-09-13 00:20:06

I have a regex match object in Python. I want to get the text it matched. Say if the pattern is '1.3', and the search string is 'abc123xyz', I want to get '123'. How can I do that?

我在Python中有一个正则表达式匹配对象。我想得到它匹配的文字。假设模式是'1.3',搜索字符串是'abc123xyz',我想得到'123'。我怎样才能做到这一点?

I know I can use match.string[match.start():match.end()], but I find that to be quite cumbersome (and in some cases wasteful) for such a basic query.

我知道我可以使用match.string [match.start():match.end()],但我发现这样的基本查询非常麻烦(在某些情况下会浪费)。

Is there a simpler way?

有更简单的方法吗?

2 个解决方案

#1


7  

You can simply use the match object's group function, like:

您可以简单地使用匹配对象的组功能,如:

match = re.search(r"1.3", "abc123xyz")
if match:
    doSomethingWith(match.group(0))

to get the entire match. EDIT: as thg435 points out, you can also omit the 0 and just call match.group().

得到整场比赛。编辑:正如thg435指出的那样,你也可以省略0并调用match.group()。

Addtional note: if your pattern contains parentheses, you can even get these submatches, by passing 1, 2 and so on to group().

附加说明:如果您的模式包含括号,您甚至可以通过将1,2传递给group()来获得这些子匹配。

#2


-1  

You need to put the regex inside "()" to be able to get that part

你需要把正则表达式放在“()”里面才能得到那个部分

>>> var = 'abc123xyz'
>>> exp = re.compile(".*(1.3).*")
>>> exp.match(var)
<_sre.SRE_Match object at 0x691738>
>>> exp.match(var).groups()
('123',)
>>> exp.match(var).group(0)
'abc123xyz'
>>> exp.match(var).group(1)
'123'

or else it will not return anything:

否则它不会返回任何东西:

>>> var = 'abc123xyz'
>>> exp = re.compile("1.3")
>>> print exp.match(var)
None

#1


7  

You can simply use the match object's group function, like:

您可以简单地使用匹配对象的组功能,如:

match = re.search(r"1.3", "abc123xyz")
if match:
    doSomethingWith(match.group(0))

to get the entire match. EDIT: as thg435 points out, you can also omit the 0 and just call match.group().

得到整场比赛。编辑:正如thg435指出的那样,你也可以省略0并调用match.group()。

Addtional note: if your pattern contains parentheses, you can even get these submatches, by passing 1, 2 and so on to group().

附加说明:如果您的模式包含括号,您甚至可以通过将1,2传递给group()来获得这些子匹配。

#2


-1  

You need to put the regex inside "()" to be able to get that part

你需要把正则表达式放在“()”里面才能得到那个部分

>>> var = 'abc123xyz'
>>> exp = re.compile(".*(1.3).*")
>>> exp.match(var)
<_sre.SRE_Match object at 0x691738>
>>> exp.match(var).groups()
('123',)
>>> exp.match(var).group(0)
'abc123xyz'
>>> exp.match(var).group(1)
'123'

or else it will not return anything:

否则它不会返回任何东西:

>>> var = 'abc123xyz'
>>> exp = re.compile("1.3")
>>> print exp.match(var)
None