php - 通过忽略括号匹配模式
问题描述
我有一个字符串,我想知道模式的第一个位置。但只有在没有用括号括起来的情况下才能找到它。
示例字符串:“ This is a (first) test with the first hit
”
我想知道第二个first
=> 32 的位置。要匹配它,(first)
必须忽略它,因为它包含在括号中。
我试过这个:
preg_match(
'/^(.*?)(first)/',
"This is a (first) test with the first hit",
$matches
);
$result = strlen( $matches[2] );
它工作正常,但结果是第一场比赛的位置(11)。
所以我需要改变.*?
.
我试图用它替换它,.(?:\(.*?\))*?
希望括号内的所有字符都将被忽略。
但这根本不匹配。
解决方案
/(?<!\()first(?!\))/
您可以使用负面展望?!运营商背后的负面看法?
preg_match(
'/(?<!\()first(?!\))/',
"This is a (first) test with the first hit",
$matches
);
这仅匹配未包含在括号中的文本,或者如果不需要任何以括号开头的单词,您可以只检查单词的开头
/(?<!\()first/
推荐阅读
- apache-kafka - 使用 kafka-consumer-groups.sh 脚本删除消费者组是删除消费者组元数据的安全方法吗?
- swift - 如何在 Swift 中启用来自 WKWebView 的网络通知?
- javascript - 对给定初始值的对象数组进行排序,使其始终排在第一位
- python - 在 jupyter notebook 中解析 argv 时出现“EOFError: EOF”
- c - 为什么当 INT_MIN 除以 -1 时使用 SIGFPE
- node.js - React Native 无法正常启动 js 服务器
- c# - 对自定义网格中的单元格使用线程
- c# - SSRS 表达式帮助多个条件
- java - 将数组中出现的字符打印到二维数组
- cypress - Reference Error :cy is not defined while running cypress test