Extract substrings between any pair of delimiters
Last Updated :
24 Mar, 2023
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
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print strings present
// between any pair of delimiters
void 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 Code
int main()
{
string str = "[This is first] ignored text [This is second]";
printSubsInDelimiters(str);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to print Strings present
// between any pair of delimiters
static 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 Code
public static void main(String[] args)
{
String str = "[This is first] ignored text [This is second]";
printSubsInDelimiters(str);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 Program to implement
# the above approach
# Function to print strings present
# between any pair of delimiters
def 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 Code
if __name__ == "__main__" :
string = "[This is first] ignored text [This is second]";
printSubsInDelimiters(string);
# This code is contributed by AnkThon
C#
// C# program to implement
// the above approach
using System;
using System.Collections;
class GFG{
// Function to print strings present
// between any pair of delimiters
static 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 Code
static void Main()
{
string str = "[This is first] ignored text [This is second]";
printSubsInDelimiters(str);
}
}
// This code is contributed by divyesh072019
JavaScript
<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>
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++
// C++ program to implement
// the above approach
#include <iostream>
#include <regex>
using namespace std;
// Function to print Strings present
// between any pair of delimiters
void 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 Code
int 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
// Java program to implement
// the above approach
import java.util.regex.*;
class GFG{
// Function to print Strings present
// between any pair of delimiters
public 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 code
public static void main(String args[])
{
// Input String
String str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimiters(str);
}
}
Python3
# Python3 program to implement
# the above approach
import re
# Function to print Strings present
# between any pair of delimiters
def 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 String
str = "[This is first] ignored text [This is second]"
# Function Call
printSubsInDelimiters(str)
# This code is contributed by yuvraj_chandra
C#
// C# program to implement
// the above approach
using System;
using System.Text.RegularExpressions;
class GFG{
// Function to print Strings present
// between any pair of delimiters
public static void printSubsInDelimiters(string str)
{
// Regex to extract the string
// between two delimiters
string regex = "\\[(.*?)\\]";
// Compile the Regex.
Regex p = new Regex(regex);
// Find match between given string
// and regular expression
// using Pattern.matcher()
Match m = p.Match(str);
// Get the subsequence
// using find() method
while (m.Success)
{
Console.WriteLine(m.Value);
m=m.NextMatch();
}
}
// Driver code
public static void Main()
{
// Input String
string str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimiters(str);
}
}
// This code is contributed by Aman Kumar.
JavaScript
// Javascript program to implement
// the above approach
// Function to print Strings present
// between any pair of delimiters
function printSubsInDelimiters(str)
{
// Regex to extract the string
// between two delimiters
let regex = "\\[(.*?)\\]";
// Find match between given string
// and regular expression
// using str.matchAll
let matches = [...str.matchAll(regex)];
// Print the matches
for(let match in matches)
{
console.log(matches[(match][1])+"<br>");
}
}
// Driver code
// Input String
let str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimiters(str);
// This code is contributed by Pushpesh Raj.
Output: This is first
This is second
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Split the string into substrings using delimiter
Given a string and a delimiter character. Split the string based on the delimiter and print the list of resulting sub strings. Examples: Input : str = "geeks;for;geeks" d_ch = ';' Output : geeks for geeks Input : str = "##ayush##jauhari####" d_ch = '#' Output : ayush jauhari Source: Microsoft IDC Ba
6 min read
Perl - Extracting Date from a String using Regex
In Perl generally, we have to read CSV (Comma Separated Values) files to extract the required data. Sometimes there are dates in the file name like sample 2014-02-12T11:10:10.csv or there could be a column in a file that has a date in it. These dates can be of any pattern like YYYY-MM-DDThh:mm:ss or
5 min read
Find an equal point in a string of brackets
Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. '(' and ')'.An equal point is an index such that the number of opening brackets be
7 min read
C++ String to Vector Using Delimiter
Delimiters are used as separators between the characters or words in a string so that different results can get separated by the delimiter. In this article let us see the different ways in which a string with delimiters can be converted to a vector of words after getting separated by delimiters.Exam
5 min read
Extracting all Email Ids in any given String using Regular Expressions
Given a string str, the task is to extract all the Email ID's from the given string.Example:Input: "Please send your resumes to Hr@[email protected] for any business inquiry please mail us at business@[email protected]"Output: Hr@[email protected]@[email protected]
4 min read
Extracting all present dates in any given String using Regular Expressions
Given a string Str, the task is to extract all the present dates from the string. Dates can be in the format i.e., mentioned below: DD-MM-YYYYYYYY-MM-DDDD Month YYYY Examples: Input: Str = "The First Version was released on 12-07-2008.The next Release will come on 12 July 2009. The due date for paym
6 min read
Enclose given Substrings of the String in parenthesis
Given a string S and a list of strings subs[] that stores the substrings of S and all the substrings are present only once, the task is to enclose the substrings of S that exists in subs[] in parentheses. If substrings in subs[] overlap each other or are consecutive then merge them into one set of p
11 min read
Get a Substring in C
A substring is a contiguous sequence of characters within a string. In this article, we will learn how to extract a substring using a C program.The simplest method to get a substring from a larger string is by using strncpy() function. Letâs take a look at an example:C++#include <stdio.h> #inc
2 min read
Reduce string by removing outermost parentheses from each primitive substring
Given a string S of valid parentheses "(" and ")", the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S. A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are
9 min read
Extract URLs present in a given string
Given a string S, the task is to find and extract all the URLs from the string. If no URL is present in the string, then print "-1". Examples: Input: S = âWelcome to https://www.geeksforgeeks.org Computer Science PortalâOutput: https://www.geeksforgeeks.orgExplanation:The given string contains the U
5 min read