[英]Regex to get character not between two other characters
如何使用正则表达式来获取不在其他两个字符/单词之间的字符/单词?
例如,在:
hello world [hello hello] world hello [world hello world hello] world hello [hello] hello
它会选择:
你好世界[你好你好]世界你好[世界你好世界你好]世界你好[你好]你好
这个问题获取文本,而不是在两个字符之间( (?<=^|\\])[^[]+
),这是接近的,除此之外,所有需要做的就是从中选择特定的单词。
您可以通过选择不需要的内容来采取相反的方法,即从左方括号到右方括号。 然后使用交替使用|
并捕捉您想要保留的内容。
使用exampole re.findall你得到捕获组的值,然后你可以过滤掉空字符串。
\[[^][]*]|\b(hello)\b
示例代码
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'++\1++', text) )
输出:
++hello++ world [hello hello] world ++hello++ [world hello world hello] world ++hello++
[hello] ++hello++
\\[[^][]*](*SKIP)(?!)|\\b(hello)\\
表达式匹配方括号之间的字符串,这些匹配被删除, hello
在单词边界内匹配并最终替换为regex.sub
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.