0
strs = [
    "I like to run head first into a wall (not)"
    "klsjlsk klsjdkls ,m s,mdn,mnsd,m (123)"
    "a b c d e f g h i (j?)"
]

I want to remove the " (not), (123), (j?)"

why is

re.sub(r' (\([*]\))$', '', strs(0))

not doing it and what's the proper way?

2
  • For easy regex expression testing check: regexr.com Commented Jun 21, 2019 at 17:05
  • should be re.sub(r'((\.+)\)$', '', strs[0]) by the way, you have (0) in your code. Commented Jun 21, 2019 at 17:06

3 Answers 3

1

You're using a capture group (the outside parentheses) to capture everything inside the parentheses. However, since you're not reusing that captured data, that's unnecessary. If you just want to remove all parentheses and the enclosed text at the end of a line (my guess based on what you supplied), you can do

re.sub(r'\([^\)]*\)$', '', strs[0])

Example: https://regex101.com/r/FOTTfi/1

If it's important to remove the space before the parentheses as well, just use a \s or \s+ at the start.

Yours doesn't work because [*] isn't doing what you think. It's looking for the literal *. If you want to find any number of characters, use .* instead.

Sign up to request clarification or add additional context in comments.

Comments

1

Consider the following:

import re


strs = [
    "I like to run head first into a wall (not)",
    "klsjlsk klsjdkls ,m s,mdn,mnsd,m (123)",
    "a b c d e f g h i (j?)"
]

# space(\s)
# openbracket(\()
# anychar(.*)
# smallestpossiblematch(?)
# closebracket(\))
pattern = r'\s*\(.*?\)'

# list comprehension with new strings
new = [re.sub(pattern, '', strs[i]) for i in range(len(strs))]

2 Comments

Good to have added \s. You may make it optional or multiple with \s*
I agree with your suggestion, I'll edit, thnx @Toto
0

This is the regex you need to use print re.sub(r'\([^)]*\)', '', strs[0])

2 Comments

can you break that down for me, I have trouble understanding what's happening there.
@runningmanjoe It checks for a bracket \( followed by anything that is not a bracket [^)] repeated 0 or more time * then followed by a bracket \)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.