JarochoEngineer
JarochoEngineer

Reputation: 1787

Remove spaces between two characters with Regex

I am looking for removing space between two characters at any part of the sentence. For instance, the following phrases:

R Z EXCAVATING AND LOGGING
EXCAVATING R Z AND LOGGING

should become

RZ EXCAVATING AND LOGGING
EXCAVATING RZ AND LOGGING

I have tried the following regex ([A-Z](.*?)[A-Z]), but I have not been able to get rid of the space between the two characters.

Any idea?

Upvotes: 1

Views: 127

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may use

text = re.sub(r'\b([A-Z])\s+(?=[A-Z]\b)', r'\1', text)

See the regex demo

Details

  • \b - word boundary
  • ([A-Z]) - Capturing group 1: an uppercase letter
  • \s+ - 1+ whitespaces...
  • (?=[A-Z]\b) - immediately followed with an uppercase letter not followed with a word char (letter, digit, _).

Upvotes: 1

Related Questions