[英]Regex for multiple words separated by spaces or commas
I'm trying to create regex for multiple strings separated by comma or space. 我正在尝试为逗号或空格分隔的多个字符串创建正则表达式。
Lorem Ipsum // valid
Lorem, Ipsum //valid
Lorem, Ipsum, Ipsum, Ipsum // multiple valid
Lorem // invalid without space/comma
Here is what i have so far: 这是我到目前为止:
^\w+(,\s*\w+){3}$/
You may use 你可以用
^\w+(?:(?:,\s\w+)+|(?:\s\w+)+)$
See the regex demo . 请参阅正则表达式演示 。
The regex matches: 正则表达式匹配:
^
- start of string ^
- 字符串的开头 \\w+
- 1+ word chars \\w+
- 1+单词字符 (?:
- start of an alternation group: (?:
- 交替组的开始:
(?:,\\s\\w+)+
- ,
, whitespace, 1+ word chars (?:,\\s\\w+)+
- , ,
空格,1+字字符 |
- or (?:\\s\\w+)+
- whitespace and then 1+ word chars (?:\\s\\w+)+
- 空格,然后是1+个字符 )
- end of group )
- 小组结束 $
- end of string. $
- 结束字符串。 You may shorten the pattern using a lookahead and a capturing group: 您可以使用前瞻和捕获组来缩短模式:
^\w+(?=(,?\s))(?:\1\w+)+$
See the regex demo . 请参阅正则表达式演示 。 Here, the difference is
(?=(,?\\s))(?:\\1\\w+)+
: 这里,差异是
(?=(,?\\s))(?:\\1\\w+)+
:
(?=(,?\\s))
- a positive lookahead that checks if there is an optional ,
and then a whitespace immediately to the right of the current location and captures that sequence into Group 1 (?=(,?\\s))
- 一个正向前瞻,检查是否有可选项,
然后是当前位置右侧的空格,
并将该序列捕获到组1中 (?:\\1\\w+)+
- 1 or more sequences of: (?:\\1\\w+)+
- 1个或多个序列:
\\1
- the same text captured into Group 1 \\1
- 捕获到第1组的相同文本 \\w+
- 1+ word chars. \\w+
- 1+单词字符。 See the regex demo . 请参阅正则表达式演示 。
Assuming that you want to match the whole phrase: 假设你想匹配整个短语:
^(\w+(,|\s)\s*)+\w+$
should do the trick. 应该做的伎俩。
试试这个正则表达式:
^(\w+[, ]+)*\w+$
由于以上都不适合我,我想出了这个:
/([^,\s]+)/g
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.