Extract substrings between brackets - Python Last Updated : 11 Jan, 2025 Comments Improve Suggest changes Like Article Like Report Extract substrings between bracket means identifying and retrieving portions of text that are enclosed within brackets. This can apply to different types of brackets like (), {}, [] or <>, depending on the context.Using regular expressions Regular expressions are the most efficient way to extract substrings from strings. re.findall() function allows us to match all substrings that are enclosed in brackets. Python import re s = "Welcome [GFG] to [Python]" # Extract all substrings inside brackets res = re.findall(r"\[(.*?)\]", s) print(res) Output['GFG', 'Python'] Explanation:re.findall() function finds all matches of the given pattern in the string.pattern \[.*?\] matches text enclosed in square brackets, and ensures .*? non-greedy matching.This method is efficient, especially when dealing with multiple pairs of brackets.Let’s explore some more methods and see how we can extract substrings between brackets.Table of ContentUsing string slicingUsing a loop and stackUsing split and list comprehensionUsing string slicingIf we know the exact positions of the brackets, we can use string slicing to extract the substrings. Python s = "Welcome [GFG] to [Python]" # Find positions of the first pair of brackets start = s.index("[") + 1 end = s.index("]") # Extract the substring res = s[start:end] print(res) OutputGFG Explanation:index() function locates the opening and closing brackets.String slicing extracts the substring between the brackets.This method is suitable for a single pair of brackets but less efficient for multiple pairs.Using a loop and stackWe can manually iterate through the string and use a stack to keep track of the bracket positions, extracting substrings as we encounter closing brackets. Python s = "Welcome [GFG] to [Python]" res = [] # List to store results stk = [] # Stack to track opening brackets for i, c in enumerate(s): if c == "[": # Push the index of '[' to the stack stk.append(i) elif c == "]" and stk: # When ']' is found, pop the last '[' start = stk.pop() res.append(s[start + 1:i]) # Extract substring between brackets print(res) Output['GFG', 'Python'] Explanation:for loop iterates through the string to find brackets.A stack is used to manage bracket positions, especially if brackets are nested.This method is more complex but useful for custom parsing requirements.Using split() and list comprehensionThis method splits the string by the opening bracket and uses list comprehension to extract substrings enclosed in brackets. Python s = "Welcome [GFG] to [Python]" # Split the string and extract parts between brackets parts = s.split("[") res = [p.split("]")[0] for p in parts if "]" in p] print(res) Output['GFG', 'Python'] Explanation:string is split into parts using "[" as the delimiter.List comprehension extracts substrings by splitting each part at "]".This method is simple but less efficient than regular expressions for larger strings. Comment More infoAdvertise with us Next Article Extract substrings between brackets - Python manjeet_04 Follow Improve Article Tags : Python Python Programs Python string-programs Practice Tags : python Similar Reads Python - Extract string between two substrings The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World".If the starting or ending substring is missing, handle the case appropriately (e.g., return an 3 min read Python - Extract K length substrings The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in PythonUsing List Comprehension List comprehension is t 2 min read Python | Extract Numbers in Brackets in String Sometimes, while working with Python strings, we can have a problem in which we have to perform the task of extracting numbers in strings that are enclosed in brackets. Let's discuss the certain ways in which this task can be performed. Method 1: Using regex The way to solve this task is to construc 6 min read Python - Extract date in String Given a string, the task is to write a Python program to extract date from it. Input : test_str = "gfg at 2021-01-04" Output : 2021-01-04 Explanation : Date format string found. Input : test_str = "2021-01-04 for gfg" Output : 2021-01-04 Explanation : Date format string found. Method #1 : Using re.s 4 min read Python program to extract Strings between HTML Tags Given a String and HTML tag, extract all the strings between the specified tag. Input : '<b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.' , tag = "br" Output : ['Gfg', 'Best', 'Reading CS']Explanation : All strings between "br" tag are extracted. Inpu 5 min read Python Extract Substring Using Regex Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a 2 min read Python - Extract range characters from String Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk 4 min read Python - Extract Indices of substring matches Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" Output : [0, 2, 3] Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring. Input : tes 5 min read Python - Extract Upper Case Characters Sometimes, while working with strings, we are concerned about the case sensitivity of strings and might require getting just a specific case of character in a long string. Letâs discuss certain ways in which only uppercase letters can be extracted from a string. Method #1: Using list comprehension + 6 min read Like