简体   繁体   English

我如何在python中获取匹配的正则表达式模式

[英]How can i grab the matched regex pattern in python

I have this code and its not working 我有这个代码,它不起作用

import re
mystring = "This is my test the string to match the stuff"    
p = re.compile(" the ")

Now I want to able to put the first match found in var1 and second match in var2 现在,我希望能够将在var1中找到的第一个匹配项和在var2中找到的第二个匹配项放在一起

You mean something like this? 你的意思是这样的吗?

In [3]: import re

In [4]: strs= "This is my test the string to match the stuff"

In [5]: p = re.compile(" the ")

In [6]: re.findall(p,strs)
Out[6]: [' the ', ' the ']

In [7]: var1,var2=re.findall(p,strs)

In [8]: var1,var2
Out[8]: (' the ', ' the ')

In case the number of matches returned are more than 2, then you've slice the list first. 如果返回的匹配数大于2,那么您首先要对列表进行切片。

var1,var2=[' the ', ' the ',' the '][:2]

On python 3.x you can take the advantage of the * to grab the rest of the elements in a list: 在python 3.x上,您可以利用*来获取列表中其余的元素:

In [2]: var1,var2,*extras=[' the ', ' the ','foo','bar']

In [3]: var1
Out[3]: ' the '

In [4]: var2
Out[4]: ' the '

In [5]: extras             #rest of the elements are stored in extras
Out[5]: ['foo', 'bar']

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

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