Regex for multiple words separated by spaces or commas

孤者浪人 提交于 2021-02-04 19:18:05

问题


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}$/

回答1:


You may use

^\w+(?:(?:,\s\w+)+|(?:\s\w+)+)$

See the regex demo.

The regex matches:

  • ^ - start of string
  • \w+ - 1+ word chars
  • (?: - start of an alternation group:
    • (?:,\s\w+)+ - ,, whitespace, 1+ word chars
    • | - or
    • (?:\s\w+)+ - whitespace and then 1+ word chars
  • ) - 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)) - 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
  • (?:\1\w+)+ - 1 or more sequences of:
    • \1 - the same text captured into Group 1
    • \w+ - 1+ word chars.

See the regex demo.




回答2:


Assuming that you want to match the whole phrase:

^(\w+(,|\s)\s*)+\w+$

should do the trick.




回答3:


Try this regex:

^(\w+[, ]+)*\w+$



回答4:


Since none of the above worked for me, I came up with this:

/([^,\s]+)/g


来源:https://stackoverflow.com/questions/47820687/regex-for-multiple-words-separated-by-spaces-or-commas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!