Java多次匹配同一组
我需要在一系列字符中多次匹配相同的模式 例如:对于输入的Java多次匹配同一组,java,regex,Java,Regex,我需要在一系列字符中多次匹配相同的模式 例如:对于输入的一些单词一些单词一些单词更多的单词我需要,, 我试过这样的方法: String input = "Some words <firstMatch> some words <secondMatch> some more words <ThirdMatch>"; Pattern pattern = Pattern.compile( ".*(\\<.*\\>).*" ); Matcher m = pa
一些单词一些单词一些单词更多的单词
我需要
,
,
我试过这样的方法:
String input = "Some words <firstMatch> some words <secondMatch> some more words <ThirdMatch>";
Pattern pattern = Pattern.compile( ".*(\\<.*\\>).*" );
Matcher m = pattern.matcher( input );
while ( m.find() ) {
System.out.println( m.group( 1 ) );
}
String input=“一些单词一些单词更多单词”;
Pattern=Pattern.compile(“.*(\\).*);
匹配器m=模式匹配器(输入);
while(m.find()){
系统输出println(m.group(1));
}
我得到的只是第三场比赛
有什么帮助吗?为什么您的模式会失败?
*(\\).*
inv喜欢大量回溯。首先,*
匹配除换行符以外的任何0+字符,基本上是整行字符。然后,正则表达式引擎回溯尝试适应后续模式,().*
。当它找到
。找到后,最后一个*
只与行的其余部分匹配。请注意,如果发动机未能找到
之后的
将匹配
,然后是
。由于您在while
块中使用匹配器#find()
,您将在输入字符串中找到所有不重叠的匹配项,但您需要访问.group(0)
(等于.group()
,整个匹配值),而不是.group(1)
*
是-它将尽可能匹配所有内容,直到下一个模式的最终匹配。。。您可以通过在*
符号后添加问号使其成为非贪婪的,这样匹配任意字符、任意次数的非贪婪将是*?
,并且您的模式将是:
Pattern pattern = Pattern.compile( ".*?(\\<.*\\>).*?" );
Pattern=Pattern.compile(“.*?(\\).*”);
然而,这只能让你走到一半。如果你知道你的模式会匹配多少次,你可以把它放到你的模式中
Pattern pattern = Pattern.compile( ".*?(\\<.*\\>).*?(\\<.*\\>).*?(\\<.*\\>).*?" );
Pattern=Pattern.compile(“.*(\\).*(\\).*(\\).*(\\).*”);
三场比赛 好了:)
Pattern=Pattern.compile(“(\\)”)代码>您可以使用正则表达式
[^<]*<([^>]*)>
@NicolasFilotto:是的,它也会起作用。我只想在这里明确说明,向OP展示有必要在这里访问整个比赛。我编辑了答案来解释这一点。它是有效的,但是你能解释一下这些方括号是什么意思吗?我补充了一些解释。基本上,这是一个否定的字符类,您可以像[^]
那样对其进行增强,以匹配除
之外的任何字符。我刚刚阅读了关于否定类的内容,并理解了它。谢谢你的帮助!
[^<]*<([^>]*)>
Some words <firstMatch> some words <secondMatch> some more words <ThirdMatch>
Match 1
Group 1. 12-22 `firstMatch`
Match 2
Group 1. 36-47 `secondMatch`
Match 3
Group 1. 66-76 `ThirdMatch`