Java:将两个不同点的字符串拆分为3个部分

Jer*_*lig 3 java regex string split

第一篇文章.对人好点?

学习Java.

我有一个String对象 "1 Book on wombats at 12.99"

我想将这个字符串拆分成String[]OR或者ArrayList<String>在第一个空格和"at"这个单词周围分割字符串,所以我String[]有3个字符串"1" "Book on wombats" "12.99"

我目前的解决方案是:

// 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;
  }
Run Code Online (Sandbox Code Playgroud)

所以这很好用,但肯定有更优雅的方式吗?或许正则表达式,我仍然试图得到一个好的处理.

谢谢!

alp*_*avo 6

你可以使用这种模式

^(\S+)\s(.*?)\sat\s(.*)$ 
Run Code Online (Sandbox Code Playgroud)

演示

^        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
Run Code Online (Sandbox Code Playgroud)

  • 为了爱上帝,解释所以我们可以学习? (4认同)