首页 > 解决方案 > 正则表达式与最后一个单词不匹配

问题描述

我有这个简单的正则表达式:

RegEx_Seek_1 := TDIPerlRegEx.Create{$IFNDEF DI_No_RegEx_Component}(nil){$ENDIF};
s1 := '(doesn''t|don''t|can''t|cannot|shouldn''t|wouldn''t|couldn''t|havn''t|hadn't)';
// s1 contents this text: (doesn't|don't|can't|cannot|shouldn't|wouldn't|couldn't|havn't|hadn't)
RegEx_Seek_1.MatchPattern := '(*UCP)(?m)'+s1+' (a |the )(ear|law also|multitude|son)(?(?= of)( \* | \w+ )| )([^»Ô¶ ][^ »Ô¶]\w*)';

其目标是查找带有冠词的名词,其后可以接of. 如果有of,那么我需要搜索名词\w+\*也是;动词的替代)。最后一个词应该是动词。

示例文本:

. some text . Doesn't the ear try ...
. some text doesn't the law also say ...
. some text doesn't the son bear ...
. some text . Shouldn't the multitude of words be answered? ...
. some text . Why doesn't the son of * come to eat ... 

我的结果:

Doesn't the ear try
doesn't the law also say
doesn't the son bear
Shouldn't the multitude of words

它没有得到最后一句话: doesn't the son of * come

我的计划是在最后一个词之前添加 \K 以获得动词。

排除字符: [^»Ô¶]是因为», Ô,已经代表文本中的某个标记,以描述现有动词。它们可能存在也可能不存在。我正在使用空格。制表符是分隔符,不是任何句子的一部分。

在这个正则表达式中,我包含了一个空格[^»Ô¶ ]来获取最后一个单词。

所以问题是如何更正正则表达式以获得更多行: doesn't the son of * come

编辑:

我需要在替换时引用同一组中的动词(我将引用动词)。

标签: regexdelphi

解决方案


你的错误在(?(?= of)( \* | \w+ )| ).

请记住,前瞻不会向前移动光标,因此( \* | \w+ )将匹配of ,所以现在的余数是* come无法匹配的,([^»Ô¶ ][^ »Ô¶]\w*)因为第二个字符是空格。

我想你应该匹配已经在你的条件下的,比如(?(?= of) of( \* | \w+ )| )


推荐阅读