2

How can I add space before open bracket ( if there is any character and don't add space if there is a space?

I tried with this expression:

re.sub("\[^}]*\(", ' $1', line)

But it's not working.

How can I check if there is any character before open bracket and if there is no space, add space?

cdecker
  • 4,515
  • 8
  • 46
  • 75
Robson
  • 1,207
  • 3
  • 21
  • 43

2 Answers2

1

Try sub this:

(\w)\(

With this:

\1 (

Demo

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
1

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?

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563