如何从前面的标签中提取单词或句子?
How to extract word or sentence from a preceeding tag?
如何通过正则表达式或有效的替代方法提取 word/quoted 句子?:
tag:videos
将提取 视频
tag:"my videos"
将提取 我的视频
riding ponies tag:ponies
将提取 小马
riding ponies tag:"pony rider"
将提取 小马骑手
riding ponies tag:
不会提取任何内容
支持多标签的能力也很棒,比如:
travelling the world tag:"aussie guy" country:Australia
提取 aussie guy 用于 tag: 和 Australia 用于 国家:.
目的是将其合并到搜索输入框中,以便用户可以有效地使用搜索词应用过滤器。
请告诉我该怎么做,谢谢!
要匹配所有 name:value
或 name:"value"
,您可以在 preg_match_all
函数调用中使用此 conditional sub-pattern regex:
(\w+):"?\K((?(?<=")[^"]*|\w*))
所有 name
将在捕获组 #1 中可用,value
部分将在捕获组 #2 中可用。
正则表达式分解
(\w+) # match 1 or more word characters in a group
: # match literal colon
"? # match a double quote optionally
\K # reset the matched data so fat
((?...)) # conditional sub-pattern available in 2nd captured group
?(?<=") # condition is using look-behind if previous character is "
[^"]* # TRUE: match 0 or more characters that are not "
| # or if condition fails
\w* # FALSE: match 0 or more word characters
要仅匹配 tag
和 value
,请使用此正则表达式:
\btag:"?\K((?(?<=")[^"]*|\w*))
我想这会完成你想要的:
/tag:('|")?(.+?)(|$)/m
演示:https://regex101.com/r/hN2gO2/1
PHP 用法:
preg_match_all('/tag:(\'|")?(.+?)(|$)/m', 'tag:videos
tag:"my videos"
riding ponies tag:ponies
riding ponies tag:"pony rider"
riding ponies tag:
travelling the world tag:"aussie guy" country:Australia', $match);
print_r($match[2]);
输出:
Array
(
[0] => videos
[1] => my videos
[2] => ponies
[3] => pony rider
[4] => aussie guy
)
如果 tag
可以与任何单词互换,则 \w+
.
如何通过正则表达式或有效的替代方法提取 word/quoted 句子?:
tag:videos
将提取 视频
tag:"my videos"
将提取 我的视频
riding ponies tag:ponies
将提取 小马
riding ponies tag:"pony rider"
将提取 小马骑手
riding ponies tag:
不会提取任何内容
支持多标签的能力也很棒,比如:
travelling the world tag:"aussie guy" country:Australia
提取 aussie guy 用于 tag: 和 Australia 用于 国家:.
目的是将其合并到搜索输入框中,以便用户可以有效地使用搜索词应用过滤器。
请告诉我该怎么做,谢谢!
要匹配所有 name:value
或 name:"value"
,您可以在 preg_match_all
函数调用中使用此 conditional sub-pattern regex:
(\w+):"?\K((?(?<=")[^"]*|\w*))
所有 name
将在捕获组 #1 中可用,value
部分将在捕获组 #2 中可用。
正则表达式分解
(\w+) # match 1 or more word characters in a group
: # match literal colon
"? # match a double quote optionally
\K # reset the matched data so fat
((?...)) # conditional sub-pattern available in 2nd captured group
?(?<=") # condition is using look-behind if previous character is "
[^"]* # TRUE: match 0 or more characters that are not "
| # or if condition fails
\w* # FALSE: match 0 or more word characters
要仅匹配 tag
和 value
,请使用此正则表达式:
\btag:"?\K((?(?<=")[^"]*|\w*))
我想这会完成你想要的:
/tag:('|")?(.+?)(|$)/m
演示:https://regex101.com/r/hN2gO2/1
PHP 用法:
preg_match_all('/tag:(\'|")?(.+?)(|$)/m', 'tag:videos
tag:"my videos"
riding ponies tag:ponies
riding ponies tag:"pony rider"
riding ponies tag:
travelling the world tag:"aussie guy" country:Australia', $match);
print_r($match[2]);
输出:
Array
(
[0] => videos
[1] => my videos
[2] => ponies
[3] => pony rider
[4] => aussie guy
)
如果 tag
可以与任何单词互换,则 \w+
.