Java: splitting a string into two different points into 3 parts
First message. Be nice?
Learning Java.
I have a String object "1 Book on wombats at 12.99"
I want to split this line into String[]
OR a ArrayList<String>
separating the line in the first space and around the word "at", so mine String[]
has 3 lines"1"
"Book on wombats"
"12.99"
my current solution:
// private method call from my constructor method
ArrayList<String> fields = extractFields(item);
// private method
private ArrayList<String> extractFields (String item) {
ArrayList<String> parts = new ArrayList<String>();
String[] sliceQuanity = item.split(" ", 2);
parts.add(sliceQuanity[0]);
String[] slicePrice = sliceQuanity[1].split(" at ");
parts.add(slicePrice[0]);
parts.add(slicePrice[1]);
return parts;
}
So this works great, but surely there is a more elegant way? maybe with a regex, which is what I'm still trying to figure out.
Thankyou!
source to share
This regex will return what you want: ^(\S+)\s(.*?)\sat\s(.*)$
Explanation:
^
assert position at the beginning of the line.
\S+
will match any non-white space.
\s
will match any space character.
.*?
will match any character (except newline).
\s
will match any space character again.
at
matches letters at
literally (case sensitive).
\s
will match any space character again.
(.*)$
will match any character (except newline) and assert position at the end of the line.
source to share
Here is a code snippet to get the String [] result that you requested. Using regex expression suggested in other answers:
^(\S+)\s(.*?)\sat\s(.*)$
is converted to a Java string, escaping each backslash with a different backslash, so they appear twice when the Pattern object is created.
String item = "1 Book on wombats at 12.99";
Pattern pattern = Pattern.compile("^(\\S+)\\s(.*?)\\sat\\s(.*)$");
Matcher matcher = pattern.matcher(item);
matcher.find();
String[] parts = new String[]{matcher.group(1),matcher.group(2),matcher.group(3)};
source to share