I have some test strings:
I want to make a regex which should match strings 1,2,3,4 but not 5.
So my constraints for match are:
Note:- I want only one regex to solve this problem. Because with separate regex and iteration I have already done it. I am searching for single line solution to validate my string.
The solution I have tried is:
/(?=^[xym\W]+$)((?=^([^m]*\W)?m+(\W[^m]*)?$)|(?=^([^x]*\W)?x+(\W[^x]*)?$)|(?=^([^y]*\W)?y+(\W[^y]*)?$))/
But it is matching 5th case also.
You may use
/^(?!.*\b([xym])\1*\b.*\b\1+\b)(?:\s*\b([xym])\2*\b)*\s*$/
See the regex demo .
Details
^
- start of string (?!.*\\b([xym])\\1*\\b.*\\b\\1+\\b)
- a negative lookahead that fails the match if immediately after the string start there is
.*
- any 0+ chars other than line break chars, as many as possible \\b([xym])\\1*\\b
- a whole word that consists of identical chars, x
, y
or m
.*
- any 0+ chars other than line break chars, as many as possible \\b\\1+\\b
- a whole word that consists of a char captured in Group 1 (?:\\s*\\b([xym])\\2*\\b)*
- 0 or more repetitions of
\\s*
- 0 or more whitespace chars \\b([xym])\\2*\\b
- a whole word that consists of 1 or more of the same chars, x
, y
or m
\\s*
- 0 or more whitespace chars $
- end of string.
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.