-1

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

shee8
  • 139
  • 10
  • 1
    Please show us the code for your latest attempt and where you got stuck. See also: [help/on-topic]. – Timur Shtatland Jan 04 '21 at 14:20
  • 1
    Does this answer your question? [Python program to check matching of simple parentheses](https://stackoverflow.com/questions/38833819/python-program-to-check-matching-of-simple-parentheses) – Tomerikoo Jan 04 '21 at 14:22

1 Answers1

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']
sunnytown
  • 1,844
  • 1
  • 6
  • 13
  • What if `str1 = 'UPPER([CATEGORY_NAME]+[[PRODUCT_NAME]])'`? In other words, this doesn't count nested brackets... – Tomerikoo Jan 04 '21 at 14:24