0

I am using this regex:

.+?(?=[\s,])

To find matches in strings like this:

something1, something2, something3

The desired matches would be:

something1
,
 something2
,
 something3

Notice that the matches are keeping white space on the front of the matched strings. This works fine if the string I am searching has white space after 'something3' but if there is no white space then 'something3' never matches. I can not guarantee that there will be a white space character on the end of the string. How do I modify this regex to be able to match the last 'something3' weather there is white space or not?

example

Chip
  • 129
  • 1
  • 12
  • I think you want `[^\s,]+` to match sequences of 1+ chars other than whitespace and commas. See [this demo](https://regex101.com/r/6aHuVX/1). – Wiktor Stribiżew Jan 15 '19 at 16:26
  • Yes, that is expected as per your regex, your last word is not followed by either `,` or a space, hence it won't match, but in case you want to match last word too, just have your regex like this `.+?(?=[\s,]|$)` where it sees either a whitespace or comma or end of input – Pushpesh Kumar Rajwanshi Jan 15 '19 at 16:26
  • 1
    Try `.+?(?=[\s,]|$)`, however, `[^\s,]+` is better. – Til Jan 15 '19 at 16:27
  • Sometimes I get lazy and create a temp string to be matched with an extra terminator appended to it. It works. – Logicrat Jan 15 '19 at 16:28
  • `.+?(?=[\s,]|$)` works for what I want the problem with `[^\s,]+` is that it doesn't keep the white space or match the commas. – Chip Jan 15 '19 at 16:32

0 Answers0