How to force matching a different string in an OR construct repeated n times

后端 未结 1 932
感动是毒
感动是毒 2021-01-16 12:44

I am new to regex, i am trying to validate a field the user is entering weekend days in a comma separated format and using 2 characters abbreviation for the day. i developed

相关标签:
1条回答
  • 2021-01-16 13:17

    You may use a (?!.*([a-z]{2}).*\1) negative lookahead at the start of regex to disallow repeating 2-letter values in the string (due to the string format, you do not even need word boundaries or comma context checks in the lookahead):

    ^(?!.*\b([a-z]{2})\b.*\b\1\b)(fr|sa|su|mo|tu|we|th)?(?:,(?:fr|sa|su|mo|tu|we|th)){0,5}$
    

    See the regex demo.

    The (?!.*\b([a-z]{2})\b.*\b\1\b) is a negative lookahead that fails the match if there is a duplicate two-letter chunk in the string.

    Java demo:

    String day = "fr|sa|su|mo|tu|we|th";
    String pattern = "(?!.*\\b([a-z]{2})\\b.*\\b\\1\\b)(?:" + day + ")?(?:,(?:" + day + ")){0,5}";
    if (s.matches(pattern)) {
        System.out.println("Valid!");
    } else {
        System.out.println("Invalid!");
    }
    

    Note that String#matches requires a full string match, so ^ and $ are not required.

    Note you may shorten the day part using character classes, fr|sa|su|mo|tu|we|th => fr|s[au]|mo|t[uh]|we.

    0 讨论(0)
提交回复
热议问题