1

The following code segment gives me unexpected results. But, I'd like to take right result.

Code syntax:

string parametersText = "\"parameter1\", \"parameter2\", \"parameter3\"";

    string findPattern = "(?<=\").*?(?=\"(, |$))";
    MatchCollection mc = Regex.Matches(parametersText, findPattern);

The result:

parameter1
, "parameter2
, "parameter3

But I'd like to get as following:

parameter1
parameter2
parameter3

How Can I Acheve this?

Any helps would be very appreciated.

Mesut
  • 1,845
  • 4
  • 24
  • 32

3 Answers3

2

The lookarounds do not consume characters and as such, it starts matching on the next \" and ends specifically on the next \"(, |$).

Try adding the (, |$) in the lookbehind as well:

(?<=(?:, |^)\").*?(?=\"(?:, |$))

I converted the capture groups into non-capture groups btw.

ideone demo

Jerry
  • 70,495
  • 13
  • 100
  • 144
0

Don't use Regex?

string parametersText = "\"parameter1\", \"parameter2\", \"parameter3\"";

parametersText.Split(',').Select(a => a.Replace("\"", "").Trim());

Or as per suggestions

parametersText.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim('"', ' '));
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

.* is greedy and will match as many characters as possible, thus including , " where possible. You can read up on the topic here: Greedy, Non-Greedy, All-Greedy Matching in C# Regex

Community
  • 1
  • 1
SvenS
  • 795
  • 7
  • 15