This is my sample code:
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;
}
First, I want to get tags with this pattern <([a-zA-Z0-9_]+)>
. When I used the pattern, I get 5 as a result since there are 5 tags in sampleString
. This works just fine but I want Matcher
to return only unique match.
Based on the string in the sample code, the result would be 2 since there are 2 unique tags (<username>
and <admin>
). So I build my regex based on this answer and now I have this pattern <([a-zA-Z0-9_]+)>(?!.*\1)
. I tried the pattern on Regex101 and it works just fine. But when used with the sample code, the result is still 5.
Is there anything wrong with my pattern?
Edit: Just like the linked question, I want to avoid using Maps or Lists. And I want to emphasize that I'm asking why my regex doesn't work on Java when it's supposed to work (based on Regex101 result).