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

python正则表达式$[a-zA-Z][0-9a-zA-Z]*带有禁止,python,regex,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

我正在寻找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(字符串)


如果我不需要检查这些东西,这就可以了。

要检查整个字符串,最好使用re.match函数而不是re.findall,并且也允许SPASE的模式将是这样的
^(\$[a-zA-Z\][0-9a-zA-Z\]);(\s))*$
嗯,我不完全确定你想做什么,但可能需要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']
试试这个:

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

有多个子字符串可能与模式匹配?所有的子字符串都必须与模式匹配。你想得到与模式匹配的单个子字符串吗?是的,我想要单个子字符串。我总是一次检查一个字符串。