Search code examples
regexcapture

Capturing String Right Before Comma in Regex


I am writing some raw Regex code and testing them on online testers. I want to capture a list of strings right before a comma. Specifically, I want to capture up to 3 strings right before a comma. Ex.

string string string,

I want to capture "string string string" (including spaces).

How do I do that?


Solution

  • You can use something like this if your string only ends with a comma:

    (.*?),
    

    If your string contains a comma, this should work:

    (.*),
    

    The ? makes the first pattern's capturing group as non-greedy as possible. Removing it makes the capturing group greedy.