Extract substrings between any pair of delimiters

14 Dec, 2021
Given a string str, the task is to extract the substrings present between two delimiters, i.e. ‘[‘ and ‘]’.
Examples:
Input: str = “[This is a string to be extracted]”Output: This is a string to be extractedExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Input: str= “[This is first] ignored text [This is second]”Output: This is firstThis is secondExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Stack-based Approach: Iterate over the characters of the string and insert the index of every ‘[‘ encountered into the stack. For every ‘]’ encountered, simply pop the index stored at the top of the stack and print the substring lying in between.
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){    // Stores the indices of    stack<int> dels;    for (int i = 0; i < str.size(); i++) {        // If opening delimiter        // is encountered        if (str[i] == '[') {            dels.push(i);        }         // If closing delimiter        // is encountered        else if (str[i] == ']' && !dels.empty()) {             // Extract the position            // of opening delimiter            int pos = dels.top();             dels.pop();             // Length of substring            int len = i - 1 - pos;             // Extract the substring            string ans = str.substr(                pos + 1, len);             cout << ans << endl;        }    }} // Driver Codeint main(){     string str = "[This is first] ignored text [This is second]";     printSubsInDelimiters(str);     return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print Strings present// between any pair of delimitersstatic void printSubsInDelimiters(String str){         // Stores the indices of    Stack<Integer> dels = new Stack<Integer>();    for(int i = 0; i < str.length(); i++)    {                 // If opening delimiter        // is encountered        if (str.charAt(i) == '[')        {            dels.add(i);        }         // If closing delimiter        // is encountered        else if (str.charAt(i) == ']' &&                 !dels.isEmpty())        {                         // Extract the position            // of opening delimiter            int pos = dels.peek();             dels.pop();             // Length of subString            int len = i - 1 - pos;             // Extract the subString            String ans = str.substring(                pos + 1, pos + 1 + len);             System.out.print(ans + "\n");        }    }} // Driver Codepublic static void main(String[] args){    String str = "[This is first] ignored text [This is second]";     printSubsInDelimiters(str);}} // This code is contributed by shikhasingrajput
# Python3 Program to implement# the above approach # Function to print strings present# between any pair of delimitersdef printSubsInDelimiters(string) :         # Stores the indices    dels = [];    for i in range(len(string)):                 # If opening delimiter        # is encountered        if (string[i] == '[') :            dels.append(i);         # If closing delimiter        # is encountered        elif (string[i] == ']' and len(dels) != 0) :             # Extract the position            # of opening delimiter            pos = dels[-1];            dels.pop();             # Length of substring            length = i - 1 - pos;             # Extract the substring            ans = string[pos + 1 : pos + 1 + length];             print(ans); # Driver Codeif __name__ == "__main__" :     string = "[This is first] ignored text [This is second]";     printSubsInDelimiters(string);         # This code is contributed by AnkThon
// C# program to implement// the above approachusing System;using System.Collections; class GFG{     // Function to print strings present// between any pair of delimitersstatic void printSubsInDelimiters(string str){         // Stores the indices of    Stack dels = new Stack();    for(int i = 0; i < str.Length; i++)    {                 // If opening delimiter        // is encountered        if (str[i] == '[')        {            dels.Push(i);        }           // If closing delimiter        // is encountered        else if (str[i] == ']' && dels.Count > 0)        {                         // Extract the position            // of opening delimiter            int pos = (int)dels.Peek();               dels.Pop();               // Length of substring            int len = i - 1 - pos;               // Extract the substring            string ans = str.Substring(                pos + 1, len);               Console.WriteLine(ans);        }    }} // Driver Codestatic void Main(){    string str = "[This is first] ignored text [This is second]";         printSubsInDelimiters(str);}} // This code is contributed by divyesh072019
<script>    // Javascript program to implement    // the above approach         // Function to print strings present    // between any pair of delimiters    function printSubsInDelimiters(str)    {         // Stores the indices of        let dels = [];        for(let i = 0; i < str.length; i++)        {             // If opening delimiter            // is encountered            if (str[i] == '[')            {                dels.push(i);            }             // If closing delimiter            // is encountered            else if ((str[i] == ']') &&                     (dels.length > 0))            {                 // Extract the position                // of opening delimiter                let pos = dels[dels.length - 1];                 dels.pop();                 // Length of substring                let len = i - 1 - pos;                 // Extract the substring                let ans;                if(pos < len)                {                    ans = str.substring(pos + 1,                                       len + 1);                }                else{                    ans = str.substring(pos + 1,                          len + pos + 1);                }                document.write(ans + "</br>");            }        }    }         let str = "[This is first] ignored text [This is second]";          printSubsInDelimiters(str);   </script>
This is first
This is second
 
Time Complexity: O(N)Auxiliary Space: O(N)
Space-Efficient Approach: The idea is to use Regular Expressions to solve this problem. Create a regular expression to extract the string between two delimiters as regex = “\\[(.*?)\\]” and match the given string with the Regular Expression. Print the subsequence formed.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to implement// the above approach#include <iostream>#include <regex>using namespace std; // Function to print Strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){         // Regex to extract the string    // between two delimiters    const regex pattern("\\[(.*?)\\]");         for(sregex_iterator it = sregex_iterator(        str.begin(), str.end(), pattern);        it != sregex_iterator(); it++)    {                 // flag type for determining the        // matching behavior here it is        // for matches on 'string' objects        smatch match;        match = *it;                 cout << match.str(1) << endl;    }    return;} // Driver Codeint main(){         // Input String    string str = "[This is first] ignored text [This is second]";         // Function Call    printSubsInDelimiters(str);         return 0;} // This code is contributed by yuvraj_chandra
// Java program to implement// the above approachimport java.util.regex.*; class GFG{ // Function to print Strings present// between any pair of delimiterspublic static void printSubsInDelimiters(String str){     // Regex to extract the string    // between two delimiters    String regex = "\\[(.*?)\\]";     // Compile the Regex.    Pattern p = Pattern.compile(regex);     // Find match between given string    // and regular expression    // using Pattern.matcher()    Matcher m = p.matcher(str);     // Get the subsequence    // using find() method    while (m.find())    {        System.out.println(m.group(1));    }} // Driver codepublic static void main(String args[]){         // Input String    String str = "[This is first] ignored text [This is second]";     // Function Call    printSubsInDelimiters(str);}}
# Python3 program to implement# the above approachimport re # Function to print Strings present# between any pair of delimitersdef printSubsInDelimiters(str):     # Regex to extract the string    # between two delimiters    regex = "\\[(.*?)\\]"     # Find match between given string    # and regular expression    # using re.findall()    matches = re.findall(regex, str)     # Print the matches    for match in matches:        print(match) # Driver code # Input Stringstr = "[This is first] ignored text [This is second]" # Function CallprintSubsInDelimiters(str) # This code is contributed by yuvraj_chandra
This is first
This is second
 
Time Complexity: O(N)Auxiliary Space: O(1)
 
divyesh072019
shikhasingrajput
ankthon
yuvraj_chandra
rameshtravel07
rkbhola5
gabaa406
regular-expression
substring
Technical Scripter 2020
Pattern Searching
Strings
Technical Scripter
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse the substrings of the given String according to the given Array of indices
Check if the given string is shuffled substring of another string
How to validate GUID (Globally Unique Identifier) using Regular Expression
How to check Aadhaar number is valid or not using Regular Expression
How to validate MAC address using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++