php - 使用正则表达式仅匹配一次

标签 php regex

我正在使用这个正则表达式来处理一些没有数字的单词,效果很好

(?:searchForThis|\G).+?(\b[^\d\s]+?\b)

正则表达式搜索整个文档而不仅仅是包含 searchForThis 的行的问题

因此,如果我有 2 次 searchForThis,则需要两次

我只想在第一行停止它,这样它就不会搜索之后的其他行 请问有什么帮助吗?

我在 php 中使用正则表达式

此处的问题示例:http://www.rubular.com/r/vPhk8VbqZR

在示例中您将看到:

Match 1
1.  word
Match 2
1.  worldtwo
Match 3
1.  wordfive
Match 4
1.  word
Match 5
1.  worldtwo
Match 6
1.  wordfive

但我只需要:

Match 1
1.  word
Match 2
1.  worldtwo
Match 3
1.  wordfive

你会看到它做了两次

==========按照要求编辑更多详细信息============================

在我的 php 中我有:

define('CODE_REGEX', '/(?:searchForThis|\G(?<!^)).*?(\b[a-zA-Z]+\b)/iu')

输出:

if (preg_match_all(CODE_REGEX, $content, $result))
            return trim($result[1][0].' '.$result[1][1].' '.$result[1][2].' '.$result[1][3].' '.$result[1][4].' '.$result[1][5]);

谢谢

最佳答案

您可以改用此模式:

(?:\A[\s\S]*?searchForThis|\G).*?(\b[a-z]+\b)/iu

(?:\A(?s).*?searchForThis|\G)(?-s).*?(\b[a-z]+\b)/iu

要处理第一个“searchForThis”与其他“searchForThis”或字符串末尾之间的多行,您可以使用以下命令:(通过示例字符串,您将获得“After”和“this”。)

(?:\A.*?searchForThis|\G)(?>[^a-z]++|\b[a-z]++\S)*?(?!searchForThis)(\b[a-z]+\b)/ius

注意:在所有三种模式中,由于不使用多行模式,因此您可以将 \A 替换为 ^。小心为 ruby​​ 正则表达式设计的 rubular: ruby​​ 中的 m = php 中的 s (即 dotall/singleline 模式),php 中的 m 是多行模式(行的每个开头都可以与 ^< 匹配)/)

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

相关文章:

java - 如何在java中用 "\"替换 "\\"

ios - 如何在 Swift 中使用正则表达式将匹配表达式替换为模板字符串而不是纯文本

php - #1932 - 引擎中不存在表 'xxx.xxxx',更改 php mysql xampp 版本

regex - 如何用一个命令分别用新行和制表符替换\n 和\t?

php - 将 "1 hour and 10 minutes"转换为 01 :10:00 in php

php - 使用未知键通过 PHP 将关联数组插入 MySQL

php - url解析器的正则表达式

JavaScript 正则表达式将字符串拆分为单词

php - docker 上带有 Nginx、php 7.4 fpm 和 mysql 8 的 Laravel 6 比 php 7.1 上的 Laravel 4 慢

php - ZF2 表单验证 - 不重叠的日期和时间