0

I need to check whether a string matches the following logical pattern:

string, string, string

I NEED TO USE A REGEXP and I cannot use functions.

For example the following string should match:

hello,hola, ciao,bye -> [hello,hola,ciao,bye]

The following shouldn't match:

hello -> []

I'm using this regexp right now but it's working fine only for the first string. I'm trying to exclude the single string without a comma in the second example.

([^,]+)

The following regexp doesn't work neither: isn't it supposed to match every group and then the end of the line BUT before the end of the line a comma followed by a string must be present?

([^,]+)(?<=,)$

Any ideas?

Damiano Barbati
  • 3,356
  • 8
  • 39
  • 51

3 Answers3

0

You have to match on ([^,]+),?, and iterate over each match. Regex doesn't have the concept of "arrays".

Alternatively, you can "split" on , and be done.

Daniel
  • 4,481
  • 14
  • 34
0

Try doing this with a positive look ahead :

/\w+(?=,)/g

Example with perl:

$ echo 'hello,hola, ciao,bye' | 
    perl -lne 'my @a = /\w+(?=,)/g; print join "\n", @a'
hello
hola
ciao

Or using split :

$ echo 'hello,hola, ciao,bye' |
    perl -lne 'my @a = split /[,\s]+/g; print join "\n", @a'
hello
hola
ciao
bye
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

I think what you are looking for is:

^[^,]+(?:,[^,]+)+$
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125