VOOZH about

URL: https://www.geeksforgeeks.org/dsa/extract-substrings-between-any-pair-of-delimiters/

⇱ Extract substrings between any pair of delimiters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extract substrings between any pair of delimiters

Last Updated : 23 Jul, 2025

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


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:


Output: 
This is first
This is second

 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment