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!

+3


source to share


4 answers


you can use this template

^(\S+)\s(.*?)\sat\s(.*)$ 

      



Demo

^        begining of string
(\S+)    caputre anything that is not a white space    
\s       a white space
(.*?)    capture as few as possible
\sat\s   followed by a white space, the word "at" and a white space
(.*)$    then capture anything to the end
      

+6


source


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.

+4


source


Well, it would be easier to just call .split () on the element. Store this array as String [] and then enter the code you want in your String [] into the returned ArrayList. The String.concat () method can also help.

0


source


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)};

      

0


source







All Articles