查找前面没有其他字符串的字符串 [英] Find string not preceded by other string

查看:64
本文介绍了查找前面没有其他字符串的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在此处获取 ['bar']:

<预><代码>>>>re.findall(r"(?<!\bdef )([a-zA-Z0-9.]+?)\(", "def foo(): bar()")['oo', 'bar']

这可能在单个正则表达式中吗?如果没有,我会先用这个: re.sub(r"\bdef [a-zA-Z0-9.]+", "", "def foo(): bar()")

解决方案

当前正则表达式匹配 foo 中的 oo 因为 oo( 不是以 "def " 开头.

要阻止模式在单词内部匹配,您可以使用 aa 单词边界,\b 并且修复可能看起来像 r"\b(?.

请注意,标识符可以与[a-zA-Z_][a-zA-Z0-9_] 匹配,因此您的模式可以像

re.findall(r'\b(?

请注意,re.Are.ASCII 将使 \w 只匹配 ASCII 字母、数字和 _.

查看正则表达式演示.

详情

  • \b - 一个词边界
  • (?<!\bdef\s) - 不允许 def + 当前位置左侧的空格
  • ([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*) - 捕获组 1(其值将是结果re.findall 调用):
    • [a-zA-Z_] - 一个 ASCII 字母或 _
    • \w* - 1+ 个字字符
    • (?: - 匹配一个序列的非捕获组的开始...
      • \. - 一个点
      • [a-zA-Z_] - 一个 ASCII 字母或 _
      • \w* - 1+ 个字字符
  • )* - ... 零次或多次
  • \( - 一个 ( 字符.

I want to get only ['bar'] here:

>>> re.findall(r"(?<!\bdef )([a-zA-Z0-9.]+?)\(", "def foo(): bar()")
['oo', 'bar']

Is that possible in a single regex? If not, i'll use this first: re.sub(r"\bdef [a-zA-Z0-9.]+", "", "def foo(): bar()")

解决方案

The current regex matches oo in foo because oo( is not preceded with "def ".

To stop the pattern from matching inside a word, you may use a a word boundary, \b and the fix might look like r"\b(?<!\bdef )([a-zA-Z0-9.]+?)\(".

Note that identifiers can be matched with [a-zA-Z_][a-zA-Z0-9_], so your pattern can be enhanced like

re.findall(r'\b(?<!\bdef\s)([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\(', s, re.A)

Note that re.A or re.ASCII will make \w match ASCII only letters, digits and _.

See the regex demo.

Details

  • \b - a word boundary
  • (?<!\bdef\s) - no def + space allowed immediately to the left of the current location
  • ([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*) - Capturing group 1 (its value will be the result of re.findall call):
    • [a-zA-Z_] - an ASCII letter or _
    • \w* - 1+ word chars
    • (?: - start of a non-capturing group matching a sequence of...
      • \. - a dot
      • [a-zA-Z_] - an ASCII letter or _
      • \w* - 1+ word chars
  • )* - ... zero or more times
  • \( - a ( char.

这篇关于查找前面没有其他字符串的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆