-2
import re
string1 = 'thisIsSomeText    [128Kb]'
print(string1)
string2 = re.sub('[*]', '', string1)
print(string2)
thisIsSomeText    [128Kb]
thisIsSomeText    [128Kb]

my issue is that I need to remove [filesize] from the end of a string. The syntax is killing me here and im struggling to understand what the proper format is for this.

AMC
  • 2,642
  • 7
  • 13
  • 35
Maxwell
  • 149
  • 1
  • 12
  • Does this answer your question? [What's the regular expression that matches a square bracket?](https://stackoverflow.com/questions/928072/whats-the-regular-expression-that-matches-a-square-bracket) – AMC Sep 18 '20 at 20:23

1 Answers1

2

You would need to escape your [ and ] characters with \

>>> import re
>>> string1 = 'thisIsSomeText    [128Kb]'
>>> re.sub(r'\[.*\]', '', string1)
'thisIsSomeText    '

You could also str.strip afterwards to remove the trailing whitespace

>>> re.sub(r'\[.*\]', '', string1).strip()
'thisIsSomeText'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • okay i understand escaping the brackets now. but what is the purpose of the ```.``` in there – Maxwell Sep 18 '20 at 19:51
  • The `.` means "any character" and `*` means "0 or more", so together `.*` means "0 or more of any character" between your brackets – Cory Kramer Sep 18 '20 at 19:52
  • @Maxwell, here's a pretty handy tool that you can use to explain and test regular expressions https://regex101.com/r/6F8Uwd/1 – Pranav Hosangadi Sep 18 '20 at 19:53
  • @Maxwell Star `*` is a *suffix* meaning "zero or more", so `\[*` would mean "zero or more open-brackets", which is not what you want. `.` means "any character except a newline". – wjandrea Sep 18 '20 at 19:54