You may use the following regex:
(\S)\(
And replace with r'\1 ('
. The (\S)
will capture into Group 1 any character that is not a whitespace. Since it is a consuming subpattern, no (
at the string start will get matched (there must be a character before a (
).
The backreferences are defined with a backslash in Python (or with \g<n>
syntax to make them unambiguous).
Note that to also match a (
at the beginning of a string (to add a space before the first (
in a string), use r'(?<!\s)\('
regex (with a non-consuming subpattern - a negative lookbehind (?<!\s)
that makes sure there is no whitespace character before a (
):
re.sub(r"(?<!\s)\(", r' (', "(some text)") # => " (some text)"
See the Python demo:
import re
print(re.sub(r"(\S)\(", r'\1 (', "(some text)")) # => (some text)
print(re.sub(r"(\S)\(", r'\1 (', "Text(some text)")) # => Text (some text)
print(re.sub(r"(?<!\s)\(", r' (', "(some text)")) # => (some text)
Please note the use of raw string literals to declare both the regex and the regex replacement (this helps avoid many unexpected issues). See What exactly is a “raw string regex” and how can you use it?