Regex - Words in any order

Twizzl :

Let's say I have 3 Strings which have to appear multiple times, but differently often.

  1. "ab" appears exactly 1 time
  2. "cd" appears exactly 2 times
  3. "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 short

  • ab,xx,ef,cd,ef,cd,ef // xx, is invalid

  • xx,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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=215933&siteId=1