2

I would like to create a regex that would allow me to select the white space before a comma. ie. "Happy birthday, Jimmy" The regex should select the white space "Happy()birthday, Jimmy" as it comes before a word/string containing a comma. *noted by the parenthesis.

Wyatt Morris
  • 21
  • 1
  • 5

1 Answers1

3

You can use Look Ahead to accomplish this.

If you are ok with matching every white space that comes before a comma, then check this out:

\s(?=[^,]*,)

If you only want to match the closest whitespace before the comma, check this out:

\s(?=[^,\s]*,)


  • \s indicated a whitespace character
  • (?=...) is a positive look ahead, meaning it makes sure its contents follow our matches
    • [] groups a set of possible characters to match
      • [^...] indicates that it should match with any character other than the contents
    • [^,\s] thus looks for any character which is not a whitespace or a comma
    • [^,\s]* the * tells it to look for zero to as many as possible of these
    • , we want to find a comma now that we have found all non-spaces and non-commas
Jacob Boertjes
  • 896
  • 3
  • 18