繁体   English   中英

正则表达式匹配单词和字符串结尾

[英]Regex match words and end of string

2正则表达式问题

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

如何匹配一个单词或两个单词,然后匹配一个特定的单词(如“ with”)或字符串末尾的$

我试过了

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

但这绝对是行不通的

编辑:我正在考虑匹配“去商场”和“去”,以一种方式我可以在python中分组“去”。

也许像这样?

>>> 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

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是您的朋友。

问候,米克。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM