Suppose I have a string as shown below
str1 = 'UPPER([CATEGORY_NAME]+[PRODUCT_NAME])'
the string can be any just want to count the no of '[]' pairs in a string
output required: 2
Suppose I have a string as shown below
str1 = 'UPPER([CATEGORY_NAME]+[PRODUCT_NAME])'
the string can be any just want to count the no of '[]' pairs in a string
output required: 2
You can do it like this, using regex:
import re
len(re.findall(r'\[.+?\]', str1))
This will count all bracket pairs that contain at least one character. If you also want to count empty bracket pairs, replace the +
with a *
in the regex.
len(re.findall(r'\[.*?\]', str1))
EDIT: If you want to get the contents of the brackets, you could do it by using a group inside the regex:
content = re.findall(r'\[(.*?)\]', str1)
count = len(contents)
print(content)
>>> ['CATEGORY_NAME', 'PRODUCT_NAME']