php - 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_?
谢谢,
解决方案
您可以使用
\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
)
推荐阅读
- python - 如何从 Python 中正在运行的进程中获取单个进程 ID 整数?
- javascript - 保存失败:VSCode中权限不足
- c - 如何理解 O_RDONLY = 0?
- firebase - 如何在启动时解决 Firebase CLI 错误
- typescript - 如何按时间倒序对 create-daml-app 项目中的消息进行排序?
- c++ - Why libraries automatically added?
- java - 从十进制转换为二进制Java错误
- mysql - Laravel 组和显示热门关系
- angular - Access-Control-Allow-Headers 在使用 .net core 和 angular 的预检响应中不允许请求标头字段授权
- python - Python - 从其他两个不同形状的数据框创建新数据框的最佳方法?