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