Twizzl :
Let's say I have 3 Strings which have to appear multiple times, but differently often.
"ab"
appears exactly 1 time"cd"
appears exactly 2 times"ef"
appears exactly 3 times
Let's say they have to be seperated with 1 comma.
It should match something like:
ab,ef,cd,ef,cd,ef
cd,cd,ef,ab,ef,ef
It should not match:
ab,cd,ef
// too shortab,xx,ef,cd,ef,cd,ef
// xx, is invalidxx,ab,cd,cd,ef,ef,ef
// xx, is invalid
I have found:
\b(?=\w*ab)(?=\w*cd)(?=\w*ef)[abcdcdefefef]{12}\b
but I cannot match comma and I do not want to add all words with the number of letters at the end ([abcdcdefefef]{12}), because I need to use this for a lot of bigger Strings.
Thank for helping!
Joop Eggen :
Forget regex.
Map<String, Long> expectedFreqTable = new HashMap<>();
expectedFreqTable .put("ab", 1L);
expectedFreqTable .put("cd", 2L);
expectedFreqTable .put("ef", 3L);
String[] words = input.split(",");
Map<String, Long> actualFreqTable = Stream.of(words)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
return expectedFreqTable.equals(actualFreqTable);
Regex is too complicated, and would be very hard to get right. The above is more verbose, but far easier to maintain and read.