首页 > 解决方案 > RegEX : 解析文本以获取完全匹配的字符串或末尾带有下划线的相同字符串

问题描述

我正在尝试解析 PHP 中的文本文件并根据字符串匹配对内容进行分组。

文本示例:

xxxx xxxx xx xxxx xxx foo xxx xxx xxxxx

xxxx xx foo xxx xxx xxxxxx

xx xxxxx xxxx xx xxx xx酒吧xx xxxx

xxxxxx xx xxxxx x xxxx

xxx xxxxx xx xx foo_sub1 xxx xxxx

xx foo_sub2 xxxxx xxx x xxxx

xxx xx foo1_sub1 xxx xxxx

xxxxx foo1_sub2 xxxxx xxx x xxxx

private function stringContains ($string, $substring){
    if (preg_match("~\b$substring\b~", $string)) {
        return true;
    }
}

问题是如果子字符串是 foo 它不会返回我 foo_sub,知道如何编辑我的正则表达式以包含任何 foo 和 foo_ 但不包括 foo1 或 foo1_?

谢谢,

标签: phpregexparsing

解决方案


您可以使用

\bfoo(?:_\w+)?\b

查看正则表达式演示

细节

  • \b- 单词边界
  • foo- 一些固定值
  • (?:_\w+)?- 可选部分:
    • _一个_
    • \w+- 一个或多个字母、数字或_字符
  • \b- 单词边界

PHP 演示

$str = 'xxxx xxxx xx xxxx xxx foo xxx xxx xxxxx\nxxxx xx foo xxx xxx xxxxx\nxx xxxxx xxxx xx xxx xx bar xx xxxx\nxxxxxx xx xxxxx x xxxx bar\nxxx xxxxx xx xx foo_sub1 xxx xxxx\nxx foo_sub2 xxxxx xxx x xxxx\nxxx xx foo1_sub1 xxx xxxx\nxxxxx foo1_sub2 xxxxx xxx x xxxx';
if (preg_match_all('~\bfoo(?:_\w+)?\b~', $str, $matches)) {
    print_r($matches[0]);
}

输出

Array
(
    [0] => foo
    [1] => foo
    [2] => foo_sub1
    [3] => foo_sub2
)

推荐阅读