对于所有正则表达式专家来说,这可能非常简单,但我已经花了足够多的时间试图自己找到答案。
我使用 Doc Parser,它可以让您创建文本解析规则。您可以使用正则表达式进行搜索。文档说支持 PERL 正则表达式,并且 Regex 101 站点是测试表达式的好地方,但我过去发现在 Regex 101 中工作的表达式似乎并不总是在 Doc Parser 中工作。
我正在尝试创建一个表达式来搜索三个字符串之一的最后一个实例。这三个字符串是:
i am sitting with after this meeting are
won't be included in your published notes
Single Signal
输入文本可以以三种不同的方式显示,这就是我正在寻找三个字符串之一的原因。以下是三个示例:
示例 1:
Single Signal
Two things I am sitting with after this meeting are...
- Words words words
例2:
Single Signal
- words words words
示例 3:
Single Signal
words words that end in won't be included in your published notes.
- words
我捕获的三个短语最终成为我真正从文本中提取内容的起点。
我用它作为我的核心/根表达式:
(?i)(i am sitting with after this meeting are|This is for internal
use and won't be included in your published notes|Single Signal)
并在表达式末尾尝试了各种方法来指示匹配文本中最后/最新出现的内容。
(?i)(i am sitting with after this meeting are|This is for internal
use and won't be included in your published notes|Single Signal).*?
(?i)(i am sitting with after this meeting are|This is for internal
use and won't be included in your published notes|Single Signal)+
(?i)(i am sitting with after this meeting are|This is for internal
use and won't be included in your published notes|Single Signal){1}
这在 Regex 101、PCRE2 中有效,但在 Doc Parser (Perl) 中无效:
(?i)[^(i am sitting with after this meeting are|won't be included in your published notes|Single Signal)]+$
非常感谢所有帮助。谢谢!
最佳答案
“全局”匹配——查找字符串中的所有匹配项——并捕获匹配项。然后正则表达式继续遍历字符串,但随着它的进行,它只能捕获当前的匹配项,因此我们最终得到最后一个匹配项。 Perl 语法
/(one|two|three)/g
这最终会在捕获变量中包含三个子模式中的最后一个匹配中的匹配(在列表上下文中使用时)/
一个例子
my $text = q(hi one some two or three and two more);
my @captures = $text =~ /(one|two|three)/g;
# $1 == 'two'
并且$1
(捕获)变量具有字符串two
。 (数组的最后一个元素也是如此,但我希望该工具无法创建变量并捕获它们。)
对数组的赋值会强制正则表达式进入“列表上下文”,在该上下文中它继续匹配整个字符串;这样我们就可以根据需要获得最后一次捕获。 (不必实际分配给数组,以任何方式强制列表上下文就足够了。)
我不知道“Doc Parser”是什么或者它是如何工作的,所以我不知道如何强制该工具中使用的正则表达式变体像上面那样运行,但我认为这是可能的。
关于正则表达式问题 - Perl - 搜索字符串的最后一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77456204/