Regex 正则表达式分组匹配验证

Regex 正则表达式分组匹配验证,regex,expression,Regex,Expression,我想知道是否有某种方式来证明一个分组是否产生了匹配。例如,让我们看看我想用以下两个字符串实现什么: string 1: "start magic someword anotherword test end" string 2: "start test x y z end" 我想获取包含关键字magic和test(两者)的字符串。但也存在一些问题: magic和test可能彼此不连续。例如,start magic word1测试word2 end magic和test在字符串中的顺序可能不同

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

string 1: "start magic someword anotherword test end"

string 2: "start test x y z end"
我想获取包含关键字
magic
test
(两者)的字符串。但也存在一些问题:

  • magic
    test
    可能彼此不连续。例如,
    start magic word1测试word2 end
  • magic
    test
    在字符串中的顺序可能不同,即应为
    start magic test end
    start test magic end
    提供匹配项
为了处理这个问题,我采用了以下正则表达式:

start ((w1)*(w2)*\[^(end)])+end
。。。这意味着:

  • 字符串必须以单词
    start
    开头,以
    end
    结尾
  • 以任何顺序匹配
    w1
    w2
    ,并使用其他非
    end
    的单词,感谢
    [^(end)]
  • 然后,比赛结束
该正则表达式的问题是所有字符串都匹配它,因为
[^(end)]
并且我需要丢弃实际字符串中
w1
w2
之间的单词

如果将正则表达式与字符串1匹配,则为:

start ((magic)*(test)*[^(end)])+end
。。。它应该只匹配字符串1(这就是我想要的)。但是字符串2也匹配

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

Description 此表达式将:

  • 要求字符串以
    start
    开头,后跟空格
  • 要求字符串以空格结尾,后跟
    end
  • 必须以任何顺序同时包含
    magic
    test
  • 单词
    magic
    test
    必须被至少一个空格包围
^start(?=\s)(?=.*\smagic(?=\s))(?=..\stest(?=\s)).\send(\r\n\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

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

“\*\[^\*]*(w1 | w2)[^\*]*(w1 | w2)[^\*]*\**”

要匹配字符串,请执行以下操作:“**whatever w1 | w2 whatever w1 | w2 whatever**”

不匹配字符串,如
“**无论w1 | w2**w1 | w2**”


@你能告诉我你是从哪里得到这张照片的吗?谢谢

您编写的正则表达式的功能与您认为的完全不同,它只会匹配类似于
start magic*test()n(ddn))(dend)的字符串