191

Python 2.7.1 Python正規表現を使用してパターン内の単語を抽出しようとしています

このような文字列があります

someline abc
someother line
name my_user_name is valid
some more lines

「my_user_name」という単語を抽出したい。私は次のようなことをします

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>

my_user_name を抽出するにはどうすればよいですか?

4

10 に答える 10

237

正規表現からキャプチャする必要があります。searchパターンが見つかった場合は、 を使用して文字列を取得しますgroup(index)。有効なチェックが実行されると仮定します。

>>> 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'
于 2013-03-11T14:09:16.213 に答える
86

一致するグループを使用できます。

p = re.compile('name (.*) is valid')

例えば

>>> import re
>>> p = re.compile('name (.*) is valid')
>>> s = """
... someline abc
... someother line
... name my_user_name is valid
... some more lines"""
>>> p.findall(s)
['my_user_name']

ここでは、 のすべてのインスタンスを取得するのre.findallではなく、を使用します。を使用すると、一致オブジェクトのグループからデータを取得する必要があります。re.searchmy_user_namere.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'

コメントで述べたように、正規表現を非貪欲にしたい場合があります。

p = re.compile('name (.*?) is valid')

正規表現がグループ内の他のものを取得できるようにするのではなく'name '、次の間のもののみを取得します。' is valid'' is valid'

于 2013-03-11T14:08:05.637 に答える
21

次のようなものを使用できます。

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')
于 2013-03-11T14:11:48.437 に答える
13

多分それは少し短くて理解しやすいです:

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'
于 2017-04-19T14:59:56.140 に答える
11

キャプチャ グループが必要です。

p = re.compile("name (.*) is valid", re.flags) # parentheses for capture groups
print p.match(s).groups() # This gives you a tuple of your matches.
于 2013-03-11T14:10:40.807 に答える
3

キャプチャ グループを使用して(?P<user>pattern)、辞書のようにグループにアクセスすることもできますmatch['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
于 2019-06-14T18:29:07.103 に答える