Java Program to Extract a Single Quote Enclosed String From a Larger String using Regex
Problem Statement: Given a String extract the substring enclosed in single quotes (‘) using Java Regex.
Java regex is an API for pattern matching with regular expression. ‘java.util.regex’ is a class used for CharSequence< interface in order to support matching against characters from a wide variety of input sources. It is not allowed to pass a null argument to any classes or interfaces as it will throw out an exception called <. Hence, it can be concluded ‘java.util.regex’ is containing Interface and classes as follows:
Illustration:
Input : "Out of this String required only is 'Geeks for Geeks' only'"
Output : Geeks for Geeks
Input : "The data wanted is'Java Regex'"
Output : Java Regex
Example
Java
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
public static void main(String[] args)
{
String string1
= "Out of this String I want 'Geeks for Geeks' only" ;
String string2
= "The data that I want is'Java Regex'" ;
Pattern p = Pattern.compile( ".*'([^']*)'.*" );
Matcher m1 = p.matcher(string1);
Matcher m2 = p.matcher(string2);
System.out.println( "String to be extracted : "
+ string1);
if (m1.matches()) {
System.out.println( "Extracted part : "
+ m1.group( 1 ));
}
System.out.println();
System.out.println( "String to be extracted : "
+ string2);
if (m2.matches()) {
System.out.println( "Extracted part : "
+ m2.group( 1 ));
}
}
}
|
Output
String to be extracted : Out of this String I want 'Geeks for Geeks' only
Extracted part : Geeks for Geeks
String to be extracted : The data that I want is'Java Regex'
Extracted part : Java Regex
Time complexity : O(n), where n is the length of the input strings “string1” and “string2”.
Space complexity :O(1), as the space used by the program remains constant regardless of the size of the input strings.
Last Updated :
31 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...