【问题标题】:Regex to get character not between two other characters正则表达式获取字符不在其他两个字符之间
【发布时间】:2020-09-08 19:45:10
【问题描述】:

如何使用 Regex 获取不在两个其他字符/单词之间的字符/单词?

例如,在:

hello world [hello hello] world hello [world hello world hello] world hello [hello] hello

它会选择:

你好世界[你好你好]世界你好[世界你好世界你好]世界你好[你好]你好

This question 获取文本,而不是两个字符之间 ((?<=^|\])[^[]+),这很接近,除此之外,所有需要做的就是从中选择特定的单词。

【问题讨论】:

标签: python regex regex-negation


【解决方案1】:

您可以通过选择您不想要的内容来采取相反的方法,即从左方括号到右方括号。然后使用| 替换并捕获您想要保留的内容。

re.findall 为例,获取捕获组的值,然后可以过滤掉空字符串。

\[[^][]*]|\b(hello)\b

Regex demo | Python demo

示例代码

import re
 
regex = r"\[[^][]*]|\b(hello)\b"
 
test_str = ("hello world [hello hello] world hello [world hello world hello] world hello [hello] hello")
 
print(list(filter(None, re.findall(regex, test_str))))

输出

['hello', 'hello', 'hello', 'hello']

【讨论】:

  • 如果我想更改它以匹配美元符号字符,我会怎么做?我试过\[[^][]*]|\b(\$)\b,但它只匹配括号内的东西。
  • @user-124812948 在这种情况下你可以省略单词边界\[[^][]*]|(\$)regex101.com/r/21CIVB/1
  • 我将如何使用re.sub?它似乎替换了括号内的东西。
  • @user-124812948 您可以使用 lambda 回调。如果是第 1 组,则退回替换件。否则返回比赛。见ideone.com/4vX8sh
  • 太棒了!非常感谢您所做的一切!
【解决方案2】:

使用 PyPi 正则表达式:

import regex
text='hello world [hello hello] world hello [world hello world hello] world hello [hello] hello'
print( regex.sub(r'\[[^][]*](*SKIP)(?!)|\b(hello)\b', r'++\1++', text) )

Code demo

输出:

++hello++ world [hello hello] world ++hello++ [world hello world hello] world ++hello++ 
[hello] ++hello++

\[[^][]*](*SKIP)(?!)|\b(hello)\ 表达式匹配方括号之间的字符串,这些匹配被丢弃,hello 在单词边界内匹配并最终替换为regex.sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    相关资源
    最近更新 更多