【问题标题】:Simple regex on string字符串上的简单正则表达式
【发布时间】:2021-11-20 13:39:57
【问题描述】:

我正在开发一个简单的提及系统和我的 PHP 脚本,我需要从较大的文本中提取 client:6,其中将出现一个或多个 @mention,如 @[John Doe (#6)](client:6)

例如。 This is my text how do you like it @John and do you have any thoughts @Jane

在 php 中,字符串看起来像。

This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)

我需要得到一个带有array('client:6','client:7')的数组

【问题讨论】:

  • regex101.com 上很多,但我不知道它是如何工作的,所以我只是在猜测,没有找到。

标签: php regex


【解决方案1】:

许多可能的方法之一是

@\[[^][]+\]\s*\(\K[^()]+

a demo on regex101.com


就正则表达式而言,这归结为

@          # "@" literally
\[         # "[" literally
[^][]+     # not "[" nor "]" as many times as possible
\]\s*      # followed by "]" literally + whitespaces, eventually
\(         # you name it - "(" literally
\K         # forget all what has been matched that far
[^()]+     # not "(" nor ")"

PHP 这可能是

<?php

$data = "This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)";

$regex = "~@\[[^][]+\]\s*\(\K[^()]+~";

preg_match_all($regex, $data, $matches);

print_r($matches);

?>

并且会产生

Array
(
    [0] => Array
        (
            [0] => client:6
            [1] => client:7
        )

)

a demo on ideone.com

【讨论】:

  • 这似乎在您的演示中运行良好。我会测试一下。
【解决方案2】:

\w+:\d+ 应该可以工作。

在句子中:

这是我的文字,你喜欢吗@John Doe (#6) 并做 你有什么想法@Jane Doe (#7)

它应该找到 client:6 和 client:7 。

例如,您可以使用https://regexr.com/ 实时试用您的正则表达式。

【讨论】:

  • 很酷,但如何使它更好一点,以便它只会捕获以@开头的条目。如果我只写client:10而不写@[John Smith](client:10),它就不会被捕获。
  • 这也是一个想法,首先获取所有 @ 的数组,如 array('@[John Smith](client:10)',@[Jane Smith](client:12)) 并遍历它们以获得特定的 client:10
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
相关资源
最近更新 更多