簡體   English   中英

帶有禁止的python正則表達式$ [a-zA-Z] [0-9a-zA-Z] *

[英]python regular expression $[a-zA-Z ][0-9a-zA-Z ]* with forbidding

我正在尋找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)

如果我也不必檢查那些事情,那沒關系。

要檢查整個字符串,最好使用re.match函數而不是re.findall,並且還允許使用空格的模式將像這樣^((\\$[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']

ideone演示

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM