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
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
.