【问题标题】:How to extract word or sentence from a preceeding tag?如何从前面的标签中提取单词或句子?
【发布时间】:2015-08-07 13:25:16
【问题描述】:

如何通过正则表达式或有效的替代方法提取单词/引用的句子?:

tag:videos 将提取视频

tag:"my videos" 将提取我的视频

riding ponies tag:ponies 将提取小马

riding ponies tag:"pony rider" 将提取 pony rider

riding ponies tag: 不会提取任何内容

支持多个标签的能力也很棒,比如:

travelling the world tag:"aussie guy" country:Australiatag: 提取 aussie guy,为 country: 提取 Australia

其目的是将其合并到搜索输入框中,以便用户可以有效地使用搜索词应用过滤器。

请告诉我如何做到这一点,谢谢!

【问题讨论】:

  • you 尝试了什么?此外,编写您想要的代码并不容易。从您的示例中,单词 country 也可以是标签。
  • (tag:)\w+ 是我尝试过的,不能精确工作,也没有报价检测。我对正则表达式非常缺乏经验,所以我一无所知。还。为了澄清,国家也被认为是另一个标签。我只是想确保可以从两个单独的标签中撤回这两个短语,如果这意味着有意义的话......

标签: php regex string text-extraction


【解决方案1】:

要匹配所有name:valuename:"value",您可以在preg_match_all 函数调用中使用此conditional sub-pattern regex

(\w+):"?\K((?(?<=")[^"]*|\w*))

RegEx Demo

所有name 将在捕获的组#1 中可用,value 部分将在捕获的组#2 中。

RegEx 拆分

(\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 

PHP Code Demo

要匹配 tag 并且它是 value,请使用此正则表达式:

\btag:"?\K((?(?<=")[^"]*|\w*))

【讨论】:

  • 这是完美的,唯一的问题是我将如何处理接收准确的namevalue? (PHP 方面)
  • 是的,你如何抓取让我们说只有“国家:”和“标签:”以及它的价值谢谢
  • 检查更新的答案以获取示例 PHP 代码。要回答您匹配tag 的问题,您可以使用\btag:"?\K((?(?&lt;=")[^"]*|\w*))
  • \btag:"?\K((?(?&lt;=")[^"]*|\w*)) 似乎没有提取像tag:"testing 123"这样的引用词
  • 另一个问题出现了。您如何从搜索结果中完全省略/删除“tag:testing”?示例searching hello tag:videos = searching hello
【解决方案2】:

我认为这会完成你所追求的:

/tag:('|")?(.+?)(\1|$)/m

演示:https://regex101.com/r/hN2gO2/1

PHP 用法:

preg_match_all('/tag:(\'|")?(.+?)(\1|$)/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+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多