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.
Asked
Active
Viewed 1.3k times
1 Answers
7
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:
If you only want to match the closest whitespace before the comma, check this out:
\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
- 963
- 5
- 20
-
absolutely fantastic answer! provided different options and clearly explained what to people new to regex could be a very confusing answer as well as a link to another source to learn more about this and other related regex tools. Well done!!!! – Gharbad The Weak Aug 21 '23 at 16:01