簡體   English   中英

正則表達式匹配給定索引上的一組字符

[英]Regex matching a set of characters on a given index

我在這個字符串中有一個字符串和一個 position。 我想知道這個 position 之前的最后一個非空格字符是否是給定集中的字符之一。 我可以使用正則表達式來做到這一點嗎? 我自己無法弄清楚。

帶有一組字符(?、|、:) 的示例:

foo('blah? test', pos=6) is True

foo('blah? test', pos=7) is False

在 Regex 的幫助下:

In [93]: def is_matched(text, pos, chars='?|!'): 
    ...:     text = text[:pos] 
    ...:     matched = re.search(r'.*(\S)(?=\s*$)', text) 
    ...:     return matched.group(1) in chars if matched else False 
    ...:                                                                                                                                                                                                    

In [94]: is_matched('blah? test', pos=6)                                                                                                                                                                    
Out[94]: True

In [95]: is_matched('blah? test', pos=7)                                                                                                                                                                    
Out[95]: False

.*(\S)(?=\s*$)

  • .*匹配直到最后一個非空格字符的任何字符

  • (\S)匹配最后一個非空格字符並將其放入捕獲的組中

  • 零寬度正向前瞻(?=\s*$)確保模式后跟零個空格直到結束

假設您想要 0 個索引字符串

def foo(text, pos):
    return text[pos] in ['?','|','!']

foo('blah? test', pos=4) // True
foo('blah? test', pos=5) // False

你真的不需要正則表達式。 你可以很容易地使用anylist comprehension

s = 'blah? test'
print(any(v in s[4] for v in '?|!'))

返回True

s[4]更改為s[5]會導致False

您不需要使用正則表達式:

def foo(s, pos, chars='?|!'):
    for i in range(pos - 1, -1, -1):
        if s[i] == ' ':
            continue
        return s[i] in chars
    return False

print(foo('blah? test', pos=6))

如果您必須使用正則表達式:

def foo(s, pos, chars='?|!'):
    l = re.findall(r'[^ ]', s[:pos]) # find all non-blank characters in first pos - 1 characters
    if not l:
        return False
    return l[-1] in chars

您在這里不需要正則表達式。 刪除切片末尾的空格(如果是),並比較最后一個字符

def is_matched(text, pos, chars='?|!'): 
   return text[:pos].rstrip()[-1] in chars

is_matched('blah? test', pos=6) #True
is_matched('blah? test', pos=7) #False

暫無
暫無

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

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