Python 正则表达式匹配单词和字符串结尾
2正则表达式问题 如何匹配子模式()中的一个单词或两个单词 我如何匹配一个或两个后跟特定单词(如“with”)或字符串结尾的单词$ 我试过了Python 正则表达式匹配单词和字符串结尾,python,regex,Python,Regex,2正则表达式问题 如何匹配子模式()中的一个单词或两个单词 我如何匹配一个或两个后跟特定单词(如“with”)或字符串结尾的单词$ 我试过了 (\w+\W*\w*\b)(\W*\bwith\b|$) 但它肯定不起作用 编辑: 我正在考虑匹配“go to mall”和“go to”,这样我就可以在python中对“go to”进行分组。也许是这样的 >>> import re >>> r = re.compile(r'(\w+(\W+\w+)?)(\W+wit
(\w+\W*\w*\b)(\W*\bwith\b|$)
但它肯定不起作用
编辑:
我正在考虑匹配“go to mall”和“go to”,这样我就可以在python中对“go to”进行分组。也许是这样的
>>> 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'
以下是我的想法:
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
还尝试了以下方法:
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
顺便说一句:re.VERBOSE和re.DEBUG是你的朋友
问候,,
Mick.对不起,你的问题不够清楚,我无法完全理解你想做什么。请给出一些字符串示例,以及你想从中提取什么。当你说
但它肯定不起作用时
你是说你的正则表达式匹配每一行吗?因为这就是我得到的。你的英文描述也一样。您可以将“x y与”匹配,也可以将行末尾的一个或两个单词匹配。是否要匹配“go to”等特定单词?或者匹配任意两个单词?虽然不是我想要的,但是\Z技巧为我解决了问题。一个问题是,这个问题是什么?第一组()?(xxx)中的do?表示xxx部分是可选的。因此(\w+(\w+\w+))匹配\w+\w+匹配的内容或\w+匹配的内容。@ultimatebuster:\Z不是一个技巧。。。这正是你想要的,如果你需要匹配的结束线,而不是别的。
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