Reputation: 1731
I'm trying to split the following string primarily based on whitespace. Please refer to the following example
Name:"John Adam" languge:"english" Date:" August 2011"
I need to split the text based on each parameter. For e.g.
Name:"John Adam"
languge:"english"
Date:" August 2011"
I'm not able to construct the right regex for this scenario.
Any pointers will be appreciated.
-Thanks
Upvotes: 0
Views: 277
Reputation: 400
String ourStr = "Name:\"John Adam\" languge:\"english\" Date:\" August 2011\"";
String[] newStr = ourStr.split(" ");
for(int i=0;i<newStr.length;i++) {
System.out.println(newStr[i] + "\n");
}
Output:
Name:"John Adam"
languge:"english"
Date:" August 2011"
Upvotes: 0
Reputation: 2484
you can use the class StringTokenizer
.. so to split something with whitespaces you could do something like:
String name=" Hello world 2011";
StringTokenizer tokens=new StringTokenizer(name);
while(tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}
and that should split it to:
Hello
world
2011
this little tutorial could help you: http://www.cstutoringcenter.com/tutorials/java/java5.php
Upvotes: 1
Reputation: 79838
It might be simpler not to use a regular expression. Just have a loop that looks for a colon, then for a double-quote, then another double-quote, then for whitespace. (OK, use a regular expression for the whitespace bit). As the loop proceeds, you'll get a String for the key, and a String for the value. You'd break the loop as soon as you fail to find the character that you're looking for.
Comment on this answer if it's not clear how to do this, and I'll post some code. But I think I've given you enough to get started.
Upvotes: 0
Reputation: 11779
String input = "Name:\"John Adam\" languge:\"english\" Date:\" August 2011\"";
// You can define this pattern statically.
Pattern pattern = Pattern.compile("(.*?\\:\\\".*?\\\")\\s*");
Matcher matcher = pattern.matcher(input);
List<String> keyValues = new LinkedList<String>();
while(matcher.find()){
keyValues.add(matcher.group());
}
//keyValues == [Name:"John Adam" , languge:"english" , Date:" August 2011"]
Upvotes: 4
Reputation: 86
I would look first at using String.split() in two passes: the first splitting on a space character, the second on double-quotes.
Upvotes: 0