[英]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.