Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 不使用';不要跳过文本_Regex_Grouping_Matching - Fatal编程技术网

Regex 不使用';不要跳过文本

Regex 不使用';不要跳过文本,regex,grouping,matching,Regex,Grouping,Matching,我知道我的问题措辞不太好,但我想不出另一种说法。假设我有以下文本,我想对其进行正则表达式匹配: Some random text here <STARTTAG1>text to match<ENDTAG1> some more random text <STARTTAG2>text to match<ENDTAG2> more random text Some random text here <STARTTAG1>I don't

我知道我的问题措辞不太好,但我想不出另一种说法。假设我有以下文本,我想对其进行正则表达式匹配:

Some random text here <STARTTAG1>text to match<ENDTAG1> some more 
random text <STARTTAG2>text to match<ENDTAG2>  more random text 
Some random text here <STARTTAG1>I don't want this text to match<ENDTAG1> some more 
random text more random text 
Some random text here <STARTTAG1>text to match<ENDTAG1> some more 
random text <STARTTAG2>text to match<ENDTAG2>  more random text 
此处有一些随机文本,以匹配更多文本
随机文本匹配更多随机文本
这里有一些随机文本,我不想让这些文本再匹配一些
随机文本更多随机文本
这里有一些随机文本,以匹配更多的文本
随机文本匹配更多随机文本
以下是我当前使用的正则表达式:

<STARTTAG1>(?<text1>.*?)<ENDTAG1>?.*?<STARTTAG2>(?<text2>.*?)<ENDTAG2>
(?*??*?(?*?)
如果在提供的文本上运行该正则表达式,则它与正确的文本对不匹配。如果在遇到另一个STARTTAG1/ENDTAG1之前没有STARTTAG2/ENDTAG2,我希望它忽略任何STARTTAG1/ENDTAG1匹配

任何帮助都将不胜感激。如果我的解释不是很好,请在文本上运行正则表达式,你就会明白我的意思(希望如此)


谢谢

子模式
*?
位于:

<STARTTAG1>(?<text1>.*?)<ENDTAG1>?.*?<STARTTAG2>(?<text2>.*?)<ENDTAG2>
                                  ^ ^
                             here |_|
这样,它可以防止子模式与中间标记匹配。但是,由于现在出现故障,正则表达式引擎将返回,并且前面的子模式:

(?<text1>.*?)
(?*?)
将尝试匹配文本:

I don't want this text to match<ENDTAG1> some more 
random text more random text 
Some random text here <STARTTAG1>text to match<ENDTAG1>
我不希望此文本与其他文本匹配
随机文本更多随机文本
这里有一些随机文本要匹配
我们可以使用相同的方法,但是我们也可以使用一种方法来防止回溯

(?><STARTTAG1>(?<text1>.*?)<ENDTAG1>)
(?>(?*?)
Regex

(?><STARTTAG1>(?<text1>.*?)<ENDTAG1>)(?:(?!<STARTTAG1>).)*?<STARTTAG2>(?<text2>.*?)<ENDTAG2>
(?>(?*?)(?:(?!)*(?*?)
  • 模式:全局+单线

漂亮!工作完美。谢谢你的解释,这有助于我理解实际发生的事情。
(?><STARTTAG1>(?<text1>.*?)<ENDTAG1>)(?:(?!<STARTTAG1>).)*?<STARTTAG2>(?<text2>.*?)<ENDTAG2>