tambourine
tambourine

Reputation: 99

How to check if string contains numbers within square brackets

I'm analysing files by name.

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?

Upvotes: 3

Views: 6518

Answers (3)

mental
mental

Reputation: 836

Use pythons stdlib re module for regex matching.

Whats regex?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern.

How do i use the re module for regex matching?

Well you can use this tutorial to help further your understandng.

The pattern you're looking for is \[\d+\] and that means to look for a constant stream of digits inside a opening and closing square brackets.

But this would be my solution to your issue using the module:

import re

if re.match('\[\d+\]', file_name):
    print('File contains numbers in square brackets')
else:
    print('File does not contain numbers in square brackets

Upvotes: 0

jwpfox
jwpfox

Reputation: 5242

Code:

import re

re_pattern = '\[(\d*)\]'
prog = re.compile(re_pattern)

teststrings = ['Kickloop [124].wav', 'Kickloop [aaa].wav']

for teststring in teststrings:
    result = prog.search(teststring)

    if result is None:
        print(teststring + ' no match')
    else:
        print(teststring + ' matched')

Output:

Kickloop [124].wav matched
Kickloop [aaa].wav no match      

More reading here: https://docs.python.org/3/library/re.html

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

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

Upvotes: 6

Related Questions