0

我想知道是否有某种方式来证明分组是否产生了匹配。例如,让我们看看我想用以下 2 个字符串完成什么:

string 1: "start magic someword anotherword test end"

string 2: "start test x y z end"

我想获取具有关键字magictest(两者)的字符串。但是有一些问题:

  • magic并且test可能彼此不连续。例如,start magic word1 test word2 end
  • magic并且test可能不在字符串中的那个顺序,即应该给 forstart magic test end和 for匹配start test magic end

为了解决这个问题,我采用了以下正则表达式:

start ((w1)*(w2)*\[^(end)])+end

... 意思是:

  • 字符串必须以单词开头并以start结尾end
  • 匹配w1andw2以任意顺序消费其他非end感谢的词[^(end)]
  • 之后,比赛结束。

该正则表达式的问题是所有字符串都匹配它,因为[^(end)]我需要丢弃实际字符串之间w1和中的单词。w2

将正则表达式与字符串 1 匹配,它将是:

start ((magic)*(test)*[^(end)])+end

...它应该只匹配字符串 1(这就是我想要的)。但字符串 2 也匹配。

是否有任何形式的检查分组是否已被正则表达式引擎匹配?遇到过类似(if \1 != null)检查magic和关键字的事情吗?test我必须用正则表达式来做,因为我无法在源代码中处理它。它旨在与命令行调用的工具一起使用。

4

2 回答 2

0

最后,我删除了 start 和 end 作为标记并将它们替换为 **。现在的表达是

"\*\* [^\*]*(w1|w2)[^\*]*(w1|w2)[^\*]* \*\*"

匹配一个字符串"** whatever w1|w2 whatever w1|w2 whatever **"

而不是匹配一个字符串"** whatever w1|w2 ** w1|w2 **"

@Denomales,你能告诉我你从哪里得到的图像吗?谢谢你

于 2013-06-22T01:23:18.757 回答
0

描述

该表达式将:

  • 要求字符串以start空格开头
  • 要求字符串以空格结尾,后跟end
  • 必须同时包含magic并且test以任何顺序包含
  • 单词magictest必须被至少一个空格包围

^start(?=\s)(?=.*\smagic(?=\s))(?=.*\stest(?=\s)).*\send(\r|\n|\Z)

在此处输入图像描述

输入文本

start magic someword anotherword test end
start test x y z end
start the a magic show with Gob and Tony Wonder who will test till the end

**输出

[0] => start magic someword anotherword test end
[1] => start the a magic show with Gob and Tony Wonder who will test till the end
于 2013-06-21T16:35:23.957 回答