问题
I have a regular expression of the following in Javascript:
/\w{1,}\s*\w{1,}/
This checks if a string has atleast two words greater than 1 character each.
Ex-
asd fgh - Valid
a b d dfd - Valid
xscxs - Invalid
I now have a new requirement that I have tried to implement, but cannot get right.
New requirement: Be able to have a comma separated list of the same type of input as before. Cannot end with a comma. Each item must be valid per the rules above.
If there are no comma then also its valid.
Also all characters are alphabets and no numbers/special characters
Valid: HOH vfdffd,dsfds dfgd,UIU fgfd
Valid: JOI JOIO
Invalid: QASW fgdfg,
Invalid: sdfds,1234 dfgdfg
Invalid: JKJ,ABCD
回答1:
You may specify the pattern for the first requirement as [a-zA-Z]+(?:\s[A-Za-z]+)+
to match 1+ letters chars and then match 1+ sequences of a whitespace + one or more word chars, and then just repeat the pattern inside another group with a comma:
/^[a-z]+(?:\s[a-z]+)+(?:,[a-z]+(?:\s[a-z]+)+)*$/i
See the regex demo (all \s
replaced with spaces in the demo since the input is one multiline string).
If multiple spaces are allowed, replace \s
with \s+
.
Details:
^
- start of string[a-z]+
- 1+ letter(?:\s[a-z]+)+
- 1 or more sequences of (i.e. a space is obligatory)\s
- a whitespace (add+
to match 1 or more occrurrences)[a-z]+
- 1+ letters
(?:,[a-z]+(?:\s[a-z]+)+)*
- zero or more sequences (i.e. a comma is optional) of,
- a comma(?:\s[a-z]+)+
- see above
$
- end of string.
回答2:
.regex(/^(?:(?![0-9]{4}|[a-zA-Z]{4})[a-zA-Z0-9]{4})(?:(?:\b\,)(?![0-9]{4}|[a-zA-Z]{4})[a-zA-Z0-9]{4})*$/)
Explanation:
(?:\b\,) -> Match with a , at the beginning of the string only if its preceded by a word boundary
(?:(?![0-9]{4}|[a-zA-Z]{4})[a-zA-Z0-9]{4}) -> Match a string with letter and digits only if dont have 4 digits ow 4 letters
来源:https://stackoverflow.com/questions/42294787/regular-expression-repeating-pattern-delimited-by-comma