【问题标题】:Matcher doesn't return unique resultMatcher 不返回唯一结果
【发布时间】:2017-12-29 13:49:11
【问题描述】:

这是我的示例代码:

public String testMethod() {
    String sampleString = "Hi <username>. Is <username> your name?. <username> rocks! <admin> wishes you well. Ask <admin> if you have any trouble!";
    String myRegex = "your regex here";

    Pattern pattern = Pattern.compile(myRegex);
    Matcher matcher = pattern.matcher(stringSample);
    int counter = 0;
    while (matcher.find()) {
        counter++;
    }

    return "Matched substring: " + counter;
}

首先,我想获得带有这种模式&lt;([a-zA-Z0-9_]+)&gt; 的标签。当我使用该模式时,我得到 5 个结果,因为 sampleString 中有 5 个标签。这很好用,但我希望 Matcher 只返回唯一匹配项。

根据示例代码中的字符串,结果将为 2,因为有 2 个唯一标签(&lt;username&gt;&lt;admin&gt;)。所以我基于this answer 构建了我的正则表达式,现在我有了这个模式&lt;([a-zA-Z0-9_]+)&gt;(?!.*\1)。我在Regex101 上尝试了该模式,效果很好。但是与示例代码一起使用时,结果仍然是 5。

我的模式有什么问题吗?

编辑: 就像链接的问题一样,我想避免使用地图或列表。我想强调一下,我在问为什么我的正则表达式在 Java 上应该可以工作时却不能工作(基于 Regex101 结果)。

【问题讨论】:

  • 您正在将正则表达式用于它们不是为它们设计的东西。用于查找模式的正则表达式。 Sets 是查找事物所有独特事件的正确工具。不要尝试使用正则表达式来解决所有问题——这是初学者的常见错误。
  • 为什么要避免使用MapList?每次你使用一个时,有人会惩罚你 100 美元吗?如果不是,您有什么动机避免使用可能适合该工作的工具?
  • @ajb 啊哈哈哈哈。好问题。我只是想了解正则表达式可以做什么。
  • Java 正则表达式功能强大。它们可用于查找各种复杂的模式。他们也有能力让你的代码在不必要的情况下变得不可读。明智地使用电源。

标签: java regex


【解决方案1】:

与其想出一个复杂的正则表达式,您可以使用简单的正则表达式 &lt;(\\w+)&gt; 并将您的结果存储在 Set 中以获得唯一匹配:

String sampleString = "Hi <username>. Is <username> your name?. <username> rocks! <admin> wishes you well. Ask <admin> if you have any trouble!";
String myRegex = "<(\\w+)>";

Pattern pattern = Pattern.compile(myRegex);
Matcher matcher = pattern.matcher(sampleString);

Set<String> tags = new HashSet<>();

while (matcher.find()) {
    tags.add(matcher.group(1));
}

System.out.printf("tags: %s, count: %d%n", tags, tags.size());

输出:

tags: [admin, username], count: 2

【讨论】:

  • 我忘了提到我想避免使用地图或列表。问题已更新。
  • 好吧 Set 既不是 Map 也不是 List :)
  • 哈哈。你让我今天一整天都感觉很好。那你叫什么MapListSet呢?收藏?
  • 是的,Collection :)
【解决方案2】:

您应该使用&lt;([a-zA-Z0-9_]+)&gt;(?!.*\\1): \\1 用于Java 代码中的第一个捕获组 而不是\1

实际的\1 是一个八进制值,查看更多信息:

What are all the escape characters in Java?

【讨论】:

  • 忘记了转义字符。谢谢,现在可以了。
猜你喜欢
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2011-11-07
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多