Python提取模式匹配
Python 2.7.1 我试图使用python正则表达式来提取模式中的单词 我有一些像这样的绳子Python提取模式匹配,python,regex,Python,Regex,Python 2.7.1 我试图使用python正则表达式来提取模式中的单词 我有一些像这样的绳子 someline abc someother line name my_user_name is valid some more lines 我想提取单词“我的用户名”。我做一些类似的事情 import re s = #that big string p = re.compile("name .* is valid", re.flags) p.match(s) #this gives me &l
someline abc
someother line
name my_user_name is valid
some more lines
我想提取单词“我的用户名”。我做一些类似的事情
import re
s = #that big string
p = re.compile("name .* is valid", re.flags)
p.match(s) #this gives me <_sre.SRE_Match object at 0x026B6838>
重新导入
s=#那根大绳子
p=re.compile(“name.*有效”,re.flags)
p、 匹配#这让我
现在如何提取我的\u用户名?您可以使用匹配组:
p = re.compile('name (.*) is valid')
e、 g
在这里,我使用re.findall
而不是re.search
来获取my\u user\u name
的所有实例。使用re.search
,您需要从匹配对象上的组中获取数据:
>>> p.search(s) #gives a match object or None if no match is found
<_sre.SRE_Match object at 0xf5c60>
>>> p.search(s).group() #entire string that matched
'name my_user_name is valid'
>>> p.search(s).group(1) #first group that match in the string that matched
'my_user_name'
只拾取
'name'
和下一个'之间的内容是有效的(而不是允许您的正则表达式拾取组中的其他'is valid'
。您需要从正则表达式捕获。搜索模式,如果找到,使用组(索引)检索字符串
。假设执行了有效的检查:
>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1) # group(1) will return the 1st capture (stuff within the brackets).
# group(0) will returned the entire matched text.
'my_user_name'
p=re.compile(“名称(.*)有效”)
>>>结果=p.search(s)
>>>结果
>>>结果。组(1)#组(1)将返回第一次捕获(括号内的内容)。
#组(0)将返回完整的匹配文本。
“我的用户名”
您想要一个
您可以使用以下内容:
import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
name = m.group(1)
else:
raise Exception('name not found')
也许这要短一点,更容易理解:
import re
text = '... someline abc... someother line... name my_user_name is valid.. some more lines'
>>> re.search('name (.*) is valid', text).group(1)
'my_user_name'
您可以使用组(用”(“
和”)“
)来捕获字符串的一部分。然后,匹配对象的方法将为您提供组的内容:
>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0) # the entire match
'name my_user_name is valid'
>>> match.group(1) # the first parenthesized subgroup
'my_user_name'
在Python3.6+中,您也可以将其放入匹配对象中,而不必使用group()
:
下面是一种不使用组的方法(Python 3.6或更高版本):
重新搜索('2\d\d\d[01]\d[0-3]\d','report_20191207.xml')[0]
'20191207'
您还可以使用捕获组(?Ppattern)
并像访问字典一样访问该组匹配['user']
string = '''someline abc\n
someother line\n
name my_user_name is valid\n
some more lines\n'''
pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])
# my_user_name
string=''某行abc\n
其他行\n
名称我的\用户\名称有效\n
还有一些行\n“”
pattern=r'名称(?P.*)有效'
matches=re.search(模式、str(字符串)、re.DOTALL)
打印(匹配['user'])
#我的用户名
看起来你实际上是在试图提取一个名称,而只是简单地查找一个匹配项。如果是这种情况,为匹配项设置span索引是很有帮助的,我建议使用re.finditer
。作为一种快捷方式,你知道正则表达式的名称
部分的长度为5,有效
部分的长度为9,因此你可以对数据进行切片匹配文本以提取名称
注意-在您的示例中,s
看起来像是带换行符的字符串,所以下面假设是这样的
我通过谷歌找到了这个答案,因为我想将
re.search()
多个组的结果直接解压缩到多个变量中。虽然这对一些人来说可能很明显,但对我来说不是,因为我总是使用group()
在过去,所以它可能会帮助将来也不知道group*s*()
的人
可能需要非贪婪匹配…(除非用户名可以是多个单词…@JonClements——你的意思是
(.*)
?是的,这是可能的,但不是必需的,除非我们使用re.DOTALL
是-re.findall('name(.*)有效,'name jon cleements valid is valid is valid is valid'))
可能不会产生期望的结果…这对Python 2.7.1不起作用?它只打印一个模式对象?@CalmStorm--哪部分不起作用(我在Python 2.7.3上测试过)?我使用的.group
部分与您接受的答案完全相同…您确定这不是组(0)
第一次匹配?有点晚,但“是”和“否”。组(0)
返回匹配的文本,而不是第一个捕获组。代码注释是正确的,但您似乎混淆了捕获组和匹配项。组(1)
返回第一个捕获组。此类问题应强制重新编写文档。此问题涉及Python正则表达式,但不涉及OP的特定问题。此外,这基本上不会对提及3.6+索引语法的现有答案添加任何新内容。
import re
text = '... someline abc... someother line... name my_user_name is valid.. some more lines'
>>> re.search('name (.*) is valid', text).group(1)
'my_user_name'
>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0) # the entire match
'name my_user_name is valid'
>>> match.group(1) # the first parenthesized subgroup
'my_user_name'
>>> match[0] # the entire match
'name my_user_name is valid'
>>> match[1] # the first parenthesized subgroup
'my_user_name'
string = '''someline abc\n
someother line\n
name my_user_name is valid\n
some more lines\n'''
pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])
# my_user_name
## covert s to list of strings separated by line:
s2 = s.splitlines()
## find matches by line:
for i, j in enumerate(s2):
matches = re.finditer("name (.*) is valid", j)
## ignore lines without a match
if matches:
## loop through match group elements
for k in matches:
## get text
match_txt = k.group(0)
## get line span
match_span = k.span(0)
## extract username
my_user_name = match_txt[5:-9]
## compare with original text
print(f'Extracted Username: {my_user_name} - found on line {i}')
print('Match Text:', match_txt)
s = "2020:12:30"
year, month, day = re.search(r"(\d+):(\d+):(\d+)", s).groups()