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
CodePudding user response:
([\w] ,[\n]) [^ \n]
Updated answer:
(.*,\n*)*(.*)
Test Case 1(Multi Line should read up to the last comma):
Test Case 2(Multi Line if the first line doesn't contain a comma should stop there):
Test Case 3(Single Line whether contains comma or not should stop):
Test Case 4(Multi Line contains multiple words):
CodePudding user response:
If there can be a single name after Additional Names:
or multiple followed by a comma:
Additional [nN]ames[^:\n\r]*:\s*([\w-] (?:,\s*[\w-] )*)
The pattern matches:
Additional [nN]ames[^:\n\r]*:
\s*
(
Capture group 1[\w-]
Match 1 word chars or-
(?:,\s*[\w-] )*
Optionally repeat a comma, optional whitespace chars and 1 word chars or-
)
Close group 1
See a regex demo.
In Java with the doubles backslashes:
String regex = "Additional [nN]ames[^:\\n\\r]*:\\s*([\\w-] (?:,\\s*[\\w-] )*)";