Extract substrings between any pair of delimiters
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 extracted
Explanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Input: str= “[This is first] ignored text [This is second]”
Output:
This is first
This is second
Explanation: 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
#include <bits/stdc++.h>
using namespace std;
void printSubsInDelimiters(string str)
{
stack< int > dels;
for ( int i = 0; i < str.size(); i++) {
if (str[i] == '[' ) {
dels.push(i);
}
else if (str[i] == ']' && !dels.empty()) {
int pos = dels.top();
dels.pop();
int len = i - 1 - pos;
string ans = str.substr(
pos + 1, len);
cout << ans << endl;
}
}
}
int main()
{
string str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printSubsInDelimiters(String str)
{
Stack<Integer> dels = new Stack<Integer>();
for ( int i = 0 ; i < str.length(); i++)
{
if (str.charAt(i) == '[' )
{
dels.add(i);
}
else if (str.charAt(i) == ']' &&
!dels.isEmpty())
{
int pos = dels.peek();
dels.pop();
int len = i - 1 - pos;
String ans = str.substring(
pos + 1 , pos + 1 + len);
System.out.print(ans + "\n" );
}
}
}
public static void main(String[] args)
{
String str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
}
}
|
Python3
def printSubsInDelimiters(string) :
dels = [];
for i in range ( len (string)):
if (string[i] = = '[' ) :
dels.append(i);
elif (string[i] = = ']' and len (dels) ! = 0 ) :
pos = dels[ - 1 ];
dels.pop();
length = i - 1 - pos;
ans = string[pos + 1 : pos + 1 + length];
print (ans);
if __name__ = = "__main__" :
string = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(string);
|
C#
using System;
using System.Collections;
class GFG{
static void printSubsInDelimiters( string str)
{
Stack dels = new Stack();
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '[' )
{
dels.Push(i);
}
else if (str[i] == ']' && dels.Count > 0)
{
int pos = ( int )dels.Peek();
dels.Pop();
int len = i - 1 - pos;
string ans = str.Substring(
pos + 1, len);
Console.WriteLine(ans);
}
}
}
static void Main()
{
string str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
}
}
|
Javascript
<script>
function printSubsInDelimiters(str)
{
let dels = [];
for (let i = 0; i < str.length; i++)
{
if (str[i] == '[' )
{
dels.push(i);
}
else if ((str[i] == ']' ) &&
(dels.length > 0))
{
let pos = dels[dels.length - 1];
dels.pop();
let len = i - 1 - pos;
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>
|
Output:
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++
#include <iostream>
#include <regex>
using namespace std;
void printSubsInDelimiters(string str)
{
const regex pattern( "\\[(.*?)\\]" );
for (sregex_iterator it = sregex_iterator(
str.begin(), str.end(), pattern);
it != sregex_iterator(); it++)
{
smatch match;
match = *it;
cout << match.str(1) << endl;
}
return ;
}
int main()
{
string str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
return 0;
}
|
Java
import java.util.regex.*;
class GFG{
public static void printSubsInDelimiters(String str)
{
String regex = "\\[(.*?)\\]" ;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find())
{
System.out.println(m.group( 1 ));
}
}
public static void main(String args[])
{
String str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
}
}
|
Python3
import re
def printSubsInDelimiters( str ):
regex = "\\[(.*?)\\]"
matches = re.findall(regex, str )
for match in matches:
print (match)
str = "[This is first] ignored text [This is second]"
printSubsInDelimiters( str )
|
C#
using System;
using System.Text.RegularExpressions;
class GFG{
public static void printSubsInDelimiters( string str)
{
string regex = "\\[(.*?)\\]" ;
Regex p = new Regex(regex);
Match m = p.Match(str);
while (m.Success)
{
Console.WriteLine(m.Value);
m=m.NextMatch();
}
}
public static void Main()
{
string str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
}
}
|
Javascript
function printSubsInDelimiters(str)
{
let regex = "\\[(.*?)\\]" ;
let matches = [...str.matchAll(regex)];
for (let match in matches)
{
console.log(matches[(match][1])+ "<br>" );
}
}
let str = "[This is first] ignored text [This is second]" ;
printSubsInDelimiters(str);
|
Output:
This is first
This is second
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...