I need to perform a search/replace on text which contains a comma which is NOT followed by a space, to change to a comma+space.
So I can find this using:
,[^\s]
But I am struggling with the replacement; I can’t just use:
, (space, comma)
Or
& ,
As the match originally matches two characters.
Is there a way of saying ‘&’ – 1 ? or ‘&[0]’ or something which means; ‘The Matched String, but only part of it’ in the replacement argument ?
Another way of trying to ask this:
- Can I use Regex to IDENTIFY one part of my string.
- But REPLACE a (slightly different,but related) part of my string.
I could just probably replace every comma with a comma+space, but this is a little more controlled and less likely to make a change I do not need….
For example:
Original:
Hello,World.
Should become:
Hello, World.
But:
Hello, World.
Should remain as :
Hello, World.
And currently, using my (bad) pattern I have:
Original:
Hello,World
After (wrong):
Hello, orld
I’m actually using Python’s (2.6) ‘re’ module for this as it happens.
Using parantheses to capture a part of the string is one way to do it. Another possibility is to use “lookahead assertion”:
This pattern matches a comma only if it is followed by a non-whitespace character. It does not match anything followed by comma but uses that information to decide whether or not to match the comma.
For example: