Regex matching everything until you dont need a comma at end of line

Viewed 69

I have a regex problem where I want to match everything until I dont see a comma at the end. In the example here I want to capture Josh,Mike and Richard.

Current regex:

Additional [nN]ames[^:\n\r]:\s([,\sa-zA-Z0-9:/_-]+)\Rrandom

However, I cant rely on the random words section being there so my proposed solution is to have some sort of way for the regex to capture until it doesnt see a comma at the end of the line or something of that sort, but still capture the words until that point. In this example, it would stop at Richard because it doesnt see a comma at the end of line but still captures Richard. Solution would be helpful!!

Example:

Additional Names:Josh,

Mike,

Richard

random wordsa asdoajdioaj : 320

2 Answers
([\w]+,[\n])+[^ \n]+

Updated answer:

(.*,\n*)*(.*)
Test Case 1(Multi Line should read up to the last comma):

Test case 1

Test Case 2(Multi Line if the first line doesn't contain a comma should stop there):

enter image description here

Test Case 3(Single Line whether contains comma or not should stop):

enter image description here

Test Case 4(Multi Line contains multiple words):

enter image description here

If there can be a single name after Additional Names: or multiple followed by a comma:

Additional [nN]ames[^:\n\r]*:\s*([\w-:/]+(?:\s*,\s*[\w-:/]+)*)\s+

The pattern matches:

  • Additional [nN]ames Match literally
  • [^:\n\r]*: Match optional repetitions of any char excluding newlines and : and then match the :
  • \s* Match optional whitspace chars
  • ( Capture group 1
    • [\w-:/]+ Match 1+ times any of the listed characters in the character class
    • (?: Non capture group to repeat as a whole part
      • \s*,\s* match a comma between optional whitespace chars
      • [\w-:/]+ Match 1+ times any of the listed characters in the character class
    • )* Close the non capture group and optionally repeat
  • ) Close group 1
  • \s+ Match 1+ whitespace chars

See a regex demo.

In Java with the doubled backslashes:

String regex = "Additional [nN]ames[^:\\n\\r]*:\\s*([\\w-:/]+(?:\\s*,\\s*[\\w-:/]+)*)\\s+";
Related