简体   繁体   中英

How to check if string contains numbers within square brackets

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM