Regex to match white spaces before certain characters with some exceptions

Viewed 766

I have this regex ([ ][,.!?;:]) to check a string if there is a white space before some punctuation marks(,.!;:). It works quite well but I need an exception for colon (:) mark. I want a match just if the character after the colon is not a slash (/).

1 Answers

You can use

([ ](?:[,.!?;]|:(?!\/)))

Or,

(?! :\/)( [,.!?;:])

See the regex demo #1 and regex demo #2.

Details:

  • [ ] - a space (note the brackets are not useful here unless you have free spacing mode on (and not in Java)
  • (?:[,.!?;]|:(?!\/)) - either of
    • [,.!?;] - one of the chars in the set
    • | - or
    • :(?!\/) - a colon not immediately followed with a slash.

Regex #2 details

  • (?! :\/) - a negative lookahead that fails the match if there is a space, then a colon and then a / immediately to the right of the current location
  • ( [,.!?;:]) - Group 1: a space and then a char from the set.
Related