Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string contains numbers within square brackets

Tags:

python

regex

I'm analysing files by name.

  • I want to exclude files that contain numbers within square brackets.
  • I want to keep files that contain words within square brackets.

Example filename to exclude:

Kickloop [124].wav

Example filename to include:

Boomy [Kick].wav

My code currently ignores all file names including square brackets.

def contains_square_brackets(file):
    if ("[" in file) and ("]" in file):
        return True

Question: Is there a regex way of achieving what I am after?

like image 977
tambourine Avatar asked Dec 05 '25 14:12

tambourine


1 Answers

The regex r'\[\d+\]' will help you. When used correctly it will identify strings containing square brackets surrounding one or more digits.

Example:

>>> import re
>>> def has_numbers_in_square_brackets(s):
...     return bool(re.search(r'\[\d+\]', s))
... 
>>> has_numbers_in_square_brackets('Hello')
False
>>> has_numbers_in_square_brackets('Hello[123]')
True
>>> has_numbers_in_square_brackets('Hello[dog]')
False
like image 188
Ray Toal Avatar answered Dec 07 '25 04:12

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!