2010-07-19 254 views
1

2正则表达式问题正则表达式拼写单词和字符串结尾

如何匹配子模式()中的单词或2个单词?

我怎么能匹配一个字或2个字是要么其次是像“与”特定的词或字符串的$

我试图

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

结束,但它绝对不是工作

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

+1

对不起,但你的问题根本不够清楚,我不知道你正在尝试做什么。 – Robusto 2010-07-19 20:16:44

+0

给出一些字符串的例子,以及你想从中抽出什么。 – 2010-07-19 20:17:16

+0

当你说'但它绝对不能工作'你的意思是你的正则表达式匹配每一行?因为这就是我得到的。你的英文说明也是。你要么匹配“x y”,要么匹配行尾的一个或两个单词。 – cape1232 2010-07-19 20:33:56

回答

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' 
+0

虽然不是我正在寻找的东西,但\ Z技巧为我解决了这个问题。 问题是什么?在第一组中做()? – Pwnna 2010-07-19 20:47:40

+0

(xxx)?意味着部件xxx是可选的。因此(\ w +(\ W + \ w +)?)匹配任何\ w + \ W + \ w +匹配或任何\ w +匹配。 – 2010-07-19 20:51:12

+1

@ultimatebuster:** \ Z不是一个诀窍** ......如果你需要匹配行尾而没有别的东西,它正是你想要的。 – 2010-07-19 22:51:42

0

这就是我想出了:

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:

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 

与试了一下还re.VERBOSE和re.DEBUG是你的朋友。

Regards, Mick。

相关问题