简体   繁体   English

由逗号分隔的正则表达式重复模式

[英]Regular Expression Repeating Pattern delimited by comma

I have a regular expression of the following in Javascript: 我在Javascript中有以下正则表达式:

/\w{1,}\s*\w{1,}/  

This checks if a string has atleast two words greater than 1 character each. 这将检查字符串是否至少包含两个大于1个字符的单词。

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

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-zA-Z]+(?:\\s[A-Za-z]+)+以匹配1+个字母字符,然后匹配1 +个空格+ 1个序列或更多单词字符,然后用逗号重复另一组内的模式:

/^[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). 请参阅正则表达式演示 (因为输入是一个多行字符串,所有\\s替换为演示中的空格)。

If multiple spaces are allowed, replace \\s with \\s+ . 如果允许多个空格,请用\\s+替换\\s

Details : 细节

  • ^ - start of string ^ - 字符串的开头
  • [az]+ - 1+ letter [az]+ - 1+字母
  • (?:\\s[az]+)+ - 1 or more sequences of (ie a space is obligatory) (?:\\s[az]+)+ - 1个或更多序列(即空间是强制性的)
    • \\s - a whitespace (add + to match 1 or more occrurrences) \\s - 一个空格(添加+以匹配一个或多个发生)
    • [az]+ - 1+ letters [az]+ - 1+个字母
  • (?:,[az]+(?:\\s[az]+)+)* - zero or more sequences (ie a comma is optional) of (?:,[az]+(?:\\s[az]+)+)* - 零个或多个序列(即逗号是可选的)
    • , - a comma , - 一个逗号
    • (?:\\s[az]+)+ - see above (?:\\s[az]+)+ - 见上文
  • $ - end of string. $ - 结束字符串。
.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM