Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}$/
like image 637
Camila Avatar asked Dec 14 '17 19:12

Camila


People also ask

Can regex include spaces?

Yes, also your regex will match if there are just spaces.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do you indicate a space in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.


2 Answers

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.

like image 50
Wiktor Stribiżew Avatar answered Oct 08 '22 06:10

Wiktor Stribiżew


Try this regex:

^(\w+[, ]+)*\w+$
like image 36
Josh Withee Avatar answered Oct 08 '22 06:10

Josh Withee