python正则表达式$ [a-zA-Z] [0-9a-zA-Z] *带有禁止

时间:2014-04-06 16:37:39

标签: python regex

我在Python中寻找正则表达式,在字符串中找到我:

$[a-zA-Z_][0-9a-zA-Z_]*

可以有更多这样的东西,它们可以用空格分隔(\ s)

这一切都很简单,但是如果有任何与模式不匹配的话,我还需要禁止整个字符串。 (+空字符串也可以)

我会举几个例子:

$x$y0123 => OK, gives me [$x, $y0123]
$ => BAD (only $)
"" or "  \t" => OK, gives me []    
$x      @hi => BAD, cause @hi, does not match the pattern

它可以是更正规的表达式,它不必只是一个。

regex = re.compile("(\$[a-zA-Z_][0-9a-zA-Z_]*)") regex.findall(string)

如果我不必检查那些东西,那也没关系。

3 个答案:

答案 0 :(得分:0)

要检查整个字符串,最好使用re.match函数而不是re.findall和模式,这也允许spase像这样^((\$[a-zA-Z_][0-9a-zA-Z_])|(\s))*$

答案 1 :(得分:0)

嗯,我不完全确定你要做什么,但也许你需要2个正则表达式:第一个检查格式的有效性,第二个检索匹配。

import re
stuff = ["$x$y0123", "$", "", "  \t", "$x      @hi"]

p1 = re.compile(r'(?:\$[A-Z_]\w*|\s)*$', re.IGNORECASE)
p2 = re.compile(r'\$[A-Z_]\w*|\s+', re.IGNORECASE)

for thing in stuff:
    if p1.match(thing):
        print(p2.findall(thing))

将打印:

['$x', '$y0123']
[]
['  \t']

ideone demo

答案 2 :(得分:0)

试试这个:

import re
s1 = '$x$y0123 $_xyz1$B0dR_'
s2 = '$x$y0123 $_xyz1$B0dR_ @1'
s3 = '$'
s4 = '   \t'
s5 = ''

def process(s, pattern):
    '''Find substrings in s that match pattern

    if string is not completely composed of substings that match pattern
    raises AttributeError

    s --> str
    pattern --> str
    returns list
    '''
    rex = re.compile(pattern)
    matches = list()
    while s:
##        print '*'*8
##        print s1
        m = rex.match(s)
        matches.append(m)
##        print '\t', m.group(), m.span(), m.endpos    
        s = s[m.end():]
    return matches

pattern = '\$[a-zA-Z_][0-9a-zA-Z_]*'
for s in [s1, s2, s3, s4, s5]:
    print '*'*8
    # remove whitespace
    s = re.sub('\s', '', s)
    if not s:
        print 'empty string'
        continue
    try:
        matches = process(s, pattern)
    except AttributeError:
        print 'this string has bad stuff in it'
        print s
        continue
    print '\n'.join(m.group() for m in matches)

>>> 
********
$x
$y0123
$_xyz1
$B0dR_
********
this string has bad stuff in it
$x$y0123$_xyz1$B0dR_@1
********
this string has bad stuff in it
$
********
empty string
********
empty string
>>>