Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a regular expression that matches “word1, word2, word3”

Tags:

regex

php

I'm trying to construct a regular expression that would match a pattern as such:

word1, word2, word3

So basically I want "" to appear twice and to have words between them. So far I came up with:

$general_content_check = preg_match("/^.*, .*$/", $general_content);

But this matches only "" several times in a string.

Can someone help me with this please?

like image 980
Pavel Avatar asked Dec 21 '22 23:12

Pavel


1 Answers

It depends what you mean by "word" but you can start by trying this:

^[^,]+(?:, +[^,]+){2}$

Explanation:

^          Start of line/string.
[^,]+      A "word" (anything that isn't a comma - including whitespace, etc.)
(?:        Start non-capturing group
    , +    A comma then any number of spaces
    [^,]+  A word
)          Close group
{2}        Repeat group exactly two times
$          End of line/string.

Other possible definitions of "word":

  • Anything except whitespace or comma: [^\s,]+
  • Only letters in A-Z: [A-Z]+ (optionally add case-insensitive flag)
  • Any letter in Unicode in any language: \p{L}+ (not widely supported)
  • Etc...
like image 152
Mark Byers Avatar answered Dec 24 '22 11:12

Mark Byers