gpt4 book ai didi

php - 匹配第一次出现的正则表达式

转载 作者:行者123 更新时间:2023-12-02 04:44:30 24 4
gpt4 key购买 nike

我需要匹配以 \s( 开头的以下模式的第一次出现,然后是 NIC,然后是 之后的任何字符#. 后跟 56 数字。

使用正则表达式:

preg_match('/[\\s|(]NIC.*[#|.]\d{5,6}/i', trim($test), $matches1);

例子:

  1. $test = "(NIC.123456";//工作正常
  2. $test = "(NIC.123456 oldnic#65703 checking"//产生结果 (NIC.123456 oldnic#65703

但它只需要是(NIC.123456。有什么问题吗?

最佳答案

您需要为非贪婪匹配添加 ? 量词。这里 .* 匹配尽可能多的数量。

你也不需要在这里两次转义 \\s ,你可以只使用 \s 并且你可以只在你的字符类中组合选择性字符在管道 | 分隔符中添加。

另请注意,您的表达式将匹配如下所示的字符串 (NIC_CCC.123456,为避免这种情况,您可以使用单词边界 \b 匹配单词之间的边界字符而不是单词字符。

preg_match('/(?<=^|\s)\(nic\b.*?[#.]\d{5,6}/i', $test, $match);

正则表达式:

(?<=           look behind to see if there is:
^ the beginning of the string
| OR
\s whitespace (\n, \r, \t, \f, and " ")
) end of look-behind
\( '('
nic 'nic'
\b the boundary between a word char (\w) and not a word char
.*? any character except \n (0 or more times)
[#.] any character of: '#', '.'
\d{5,6} digits (0-9) (between 5 and 6 times)

参见 live demo

关于php - 匹配第一次出现的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com