问题描述
一个人如何使用正则表达式来获得一个不在其他两个字符/单词之间的字符/单词?
例如,在:
hello world [hello hello] world hello [world hello world hello] world hello [hello] hello
它将选择:
你好世界[你好你好]世界你好 [世界你好世界你好]世界你好 [你好] 你好
This question获取文本,而不是两个字符之间的文本((?<=^|\])[^[]+
),这是很接近的,在此之上要做的所有事情就是从中选择特定的单词。我是Regex的新手,所以很抱歉。任何帮助深表感谢。 (我使用的是Regex的Python风格)
解决方法
您可以选择相反的方法,选择不需要的内容,即从方括号开始到结束。然后使用$results = $wpdb-> get_results("SELECT location_code,zone_id,zone_name ".
"FROM {$wpdb->prefix}shipping_zone_locations ".
"JOIN {$wpdb->prefix}shipping_zones ".
"ON ({$wpdb->prefix}shipping_zone_locations.zone_id = {$wpdb->prefix}shipping_zones.zone_id)");
进行替换,并捕获您想要保留的内容。
使用示例杆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))))
,
使用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
替换。