Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Java Matcher没有';t返回唯一的结果_Java_Regex - Fatal编程技术网

Java Matcher没有';t返回唯一的结果

Java Matcher没有';t返回唯一的结果,java,regex,Java,Regex,这是我的示例代码: 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 rege

这是我的示例代码:

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;
}
publicstringtestmethod(){
String sampleString=“您好,您的名字是吗?.rocks!现在我有了这个模式
(?!.\1)
。我尝试了这个模式,效果很好。但是与示例代码一起使用时,结果仍然是5

我的模式有什么问题吗

编辑: 就像链接的问题一样,我想避免使用映射或列表。我想强调的是,我想问的是,为什么我的正则表达式在Java上不工作,而它应该工作(基于Regex101结果)。

你应该使用
(?!.*\\1)
\\1
用于Java中的第一个捕获组

实际
\1
是一个八进制值,请参阅以下内容:


与使用复杂正则表达式不同,您可以使用简单正则表达式
,并将结果存储在
集合中,以仅获取唯一匹配:

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());

你正在使用正则表达式来处理它们不是专门为之设计的事情。正则表达式用于查找模式。
Set
s是查找某个事物的所有唯一实例的正确工具。不要试图使用正则表达式来解决所有问题——这是初学者的一个常见错误。你为什么要避免使用
Map
List
每次使用一个正则表达式都会给你100美元?如果不是的话,你有什么动机来避免使用适合这项工作的工具?@ajb AHAHAHAHAA。好问题。我只是想了解正则表达式能做什么。Java正则表达式有很多功能。它们可以用来发现各种复杂的模式。它们还可以让你的代码变得不真实不必要的可读取。明智地使用电源。忘记转义字符。谢谢,它现在起作用了。我忘了提到我想避免使用地图或列表。问题已更新。
Set
既不是
Map
,也不是
List
:)哈哈。你让我开心了。你把
Map
List
Set叫什么然后?收藏?是的,确实是一个
收藏
:)
tags: [admin, username], count: 2