正则匹配单词及字符串结尾

1 投票
2 回答
7100 浏览
提问于 2025-04-16 01:32

2 正则表达式问题

我该如何在一个子模式 () 中匹配一个词或两个词呢?

我想匹配一个词或两个词,这个词后面要么跟着一个特定的词,比如“with”,要么就是字符串的结尾 $。

我试过

(\w+\W*\w*\b)(\W*\bwith\b|$)

但这显然不管用。

编辑:我在想要匹配“go to mall”和“go to”,这样我就可以在 Python 中把“go to”分组。

2 个回答

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

顺便说一下,re.VERBOSE 和 re.DEBUG 是你们的好帮手。

祝好,
Mick。

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'

撰写回答