Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match `"abc", "d,e", , "", ",f"` with groups

Tags:

regex

I would like to regex-match the string

"abc", "d,e"  , "", ",f"

such that the groups abc, d,e, ``, and ,f (without quotes) are separately matched.

With the group

"([^"]*)"

matching the "abc" bits, I assumed the regex

(?:\s*"([^"]*)"\s*,)\s*"([^"]*)"\s*

would do the trick. However, it only matches abc and d,e.

I've created a toy example at regex101 that shows the behavior.

Any hints?

like image 570
Nico Schlömer Avatar asked Sep 26 '22 20:09

Nico Schlömer


2 Answers

You'd want to make "following" group optional:

(?:\s*"([^"]*)"\s*)(?:,\s*"([^"]*)"\s*)?

Live demo

Update #1

Cleaner RegEx:

/\s*"([^"]+)"(?:,\s*)?/g

Update #2

Base on your last edit for including zero or more characters:

/\s*"([^"]*?)"(?:,\s*)?/g

Live demo

like image 154
revo Avatar answered Oct 11 '22 18:10

revo


Almost similar to revo's answer, but here's my regex:

/(?:"([^"]*)")(?:\s*,\s*)?/g

Live Demo

This will get correct match for "abc" , "d,e" , "", ",f" also.

like image 40
Unos Avatar answered Oct 11 '22 17:10

Unos