正则表达式获取不在其他两个字符之间的字符

Regex to get character not between two other characters

如何使用 Regex 获得不在其他两个 characters/words 之间的 character/word?

例如,在:

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

会 select:

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

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

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

例如使用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']

使用 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'++++', text) )

Code demo

输出:

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

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