The program I am writing needs to ensure that it does not have a word or sequence of chars repeated in the input string.
How can I ensure this using java pattern matching? I think this is possible if regex can memorise the patterns it has found. Or may be I am wrong.
But ultimately I want to know if this is possible using java regex.
Ex:
goneishegone \\\\ should return true - "gone" has appeared twice.
goneisheyesterday \\\\ should return false - has not repeating words. (minimum length of words that repeat should be 2 or more)
You can add the words that your regex matches into a HashSet. If the add() Method returns false, the word is already in the Set. So your solultion would look something like the following:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
Boolean return = false;
Set<String> allMatches = new HashSet<String>();
Matcher m = Pattern.compile("your regular expression here")
.matcher(yourStringHere);
while (m.find()) {
if(!allMatches.add(m.group())){
return = true;
break;
}
System.out.println(Boolean.toString(return));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.