4

I just recently attempted to learn Regex for a project, and I have this:

patternstr = "<$Testing$>Go HERE <$Test2$>GO HERE 2 ";
Pattern pattern = Pattern.compile("<\\$\\w+\\$>\\w+");
Matcher matcher = pattern.matcher(patternstr);

Which returns

<$Testing$>Go
and
<$Test2$>GO

so how do I get the rest of the text while keeping the two strings separate? Like that should return

<$Testing$>Go HERE
<$Test2$>GO HERE 2

and if I added more of the tags with text after it, it will return the third as well as the first 2.

4

2 回答 2

3

您需要添加一个(正)前瞻或负字符类

就像是:

<\\$\\w+\\$>[^<]+

或(已编辑)

<\\$\\w+\\$>.+?(?=<)

根据评论进行编辑(应该是正面的,而不是负面的前瞻性)。

我不会重复艾伦关于行尾的评论,他们是对的。

于 2013-04-21T23:03:54.617 回答
0

根据您在中间允许的内容,String这相当容易。

你只需要<$something$>something反复匹配。如果您没有<中间字符串,那么您需要做的就是

final String patternstr = "<$Testing$>Go HERE <$Test2$>GO HERE 2 ";
final Pattern pattern = Pattern.compile("<\\$([^$]++)\\$>([^<]++)");
final Matcher matcher = pattern.matcher(patternstr);
while (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

输出:

Testing
Go HERE 
Test2
GO HERE 2 

解释:

  • <\\$与开场相匹配<$
  • ([^$]++)匹配并抓取标签的内容,即直到下一个$
  • \\$>匹配结束$>
  • ([^<]++)匹配并抓住一切直到下一个<
于 2013-04-21T23:06:06.213 回答