Replacing parentheses using regex in Python

Viewed 83

I am trying to replace the parenthesis around a number or single letter (1), (a) with 1. and 2. I want to leave the longer words in place (reprehenderit)

This is what I have tried. The full stop appears on both sides of all former parentheses when I only want it to appear once.

Thank you


import re

text = '''Lorem ipsum dolor sit amet,\n\n(1)consectetur adipiscing elit, sed do eiusmod tempor incididunt\n\n(2)ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip\n\n(a) ex ea (commodo consequat). Duis aute irure dolor in (reprehenderit) in voluptate velit esse cillum dolore eu\n\n(b) fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''

result = re.sub(r'[\(\)]','.\1', text)

Print(result)

What I am getting:

Lorem ipsum dolor sit amet,

.1. consectetur adipiscing elit, sed do eiusmod tempor incididunt

.2. ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip

.a. ex ea .commodo consequat.. Duis aute irure dolor in .reprehenderit. in voluptate velit esse cillum dolore eu

.b. fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

I am looking for:

Lorem ipsum dolor sit amet,

1. consectetur adipiscing elit, sed do eiusmod tempor incididunt
2. ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
    a. ex ea (commodo consequat). Duis aute irure dolor in (reprehenderit) in voluptate velit esse cillum dolore eu
    b. fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

2 Answers
result = re.sub(r'\(([0-9a-z])\)', r'\1. ', text)

You are actually removing any ( and ) with a dot and a char with octal code \001.

If you want to replace (...) at the start of a line with one letter or digit inside use

result = re.sub(r'^\(([\da-z])\)', r'\1. ', text, flags=re.M)

See this regex demo. Note the use of ^ that enables matching at the start of a line only (it works together with flags=re.M flag).

To remove when there are 1+ digits or letters use

result = re.sub(r'^\((\d+|[a-z]+)\)', r'\1. ', text, flags=re.M)

See the regex demo. Here,

  • ^ - matches start of a line
  • \( - ( char
  • (\d+|[a-z]+) - 1 or more digits or 1 or more letters
  • \) - a ) char.
Related