Sample Input: abc def ghi "jkl mno" pqrs "tuv" wxyz
Expected Output:
abc
def
ghi
"jkl mno"
pqrs
"tuv"
wxyz
1. One of the easiest way to solve the problem statement is through Patters!!
"([^\"]\\S*|\".+?\")\\s*" - is the pattern to parse the string except double quotes.
Complete Program.
// import the required packages
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class TokenizeString
{
public static void main(String [] args) {
// user input
System.out.println("Enter the string");
// Instantiate the Scanner class
Scanner scanner=new Scanner(System.in);
// store the entire line in the variable
String queryString=sc.nextLine();
// instantiating the ArrayList object
List<String> list = new ArrayList<String>();
Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(queryString);
while (m.find())
list.add(m.group(1));
Iterator<String> i=list.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Expected Output:
abc
def
ghi
"jkl mno"
pqrs
"tuv"
wxyz
1. One of the easiest way to solve the problem statement is through Patters!!
"([^\"]\\S*|\".+?\")\\s*" - is the pattern to parse the string except double quotes.
Complete Program.
// import the required packages
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class TokenizeString
{
public static void main(String [] args) {
// user input
System.out.println("Enter the string");
// Instantiate the Scanner class
Scanner scanner=new Scanner(System.in);
// store the entire line in the variable
String queryString=sc.nextLine();
// instantiating the ArrayList object
List<String> list = new ArrayList<String>();
Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(queryString);
while (m.find())
list.add(m.group(1));
Iterator<String> i=list.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Comments
Post a Comment