2正则表达式问题
如何匹配子模式()中的单词或2个单词?
我如何匹配一个单词或两个单词,后跟一个特定单词,如“with”或字符串结尾$
我试过
(\w+\W*\w*\b)(\W*\bwith\b|$)
但它肯定无法正常工作
编辑: 我正在考虑将“go to mall”和“go to”相匹配,这样我就可以在python中组合“go to”。
答案 0 :(得分:3)
也许是这样的?
>>> import re
>>> r = re.compile(r'(\w+(\W+\w+)?)(\W+with\b|\Z)')
>>> r.search('bar baz baf bag').group(1)
'baf bag'
>>> r.search('bar baz baf with bag').group(1)
'baz baf'
>>> r.search('bar baz baf without bag').group(1)
'without bag'
>>> r.search('bar with bag').group(1)
'bar'
>>> r.search('bar with baz baf with bag').group(1)
'bar'
答案 1 :(得分:0)
以下是我提出的建议:
import re
class Bunch(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
match = re.compile(
flags = re.VERBOSE,
pattern = r"""
( (?!with) (?P<first> [a-zA-Z_]+ ) )
( \s+ (?!with) (?P<second> [a-zA-Z_]+ ) )?
( \s+ (?P<awith> with ) )?
(?![a-zA-Z_\s]+)
| (?P<error> .* )
"""
).match
s = 'john doe with'
b = Bunch(**match(s).groupdict())
print 's:', s
if b.error:
print 'error:', b.error
else:
print 'first:', b.first
print 'second:', b.second
print 'with:', b.awith
Output:
s: john doe with
first: john
second: doe
with: with
还尝试了:
s: john
first: john
second: None
with: None
s: john doe
first: john
second: doe
with: None
s: john with
first: john
second: None
with: with
s: john doe width
error: john doe width
s: with
error: with
BTW:re.VERBOSE和re.DEBUG是你的朋友。
此致 米克。