Java:将字符串在两个不同点分割成3部分

3

首帖,请友善?

正在学习Java。

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

我想将这个字符串分割成String[]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;
  }

这样做是有效的,但肯定有更优雅的方式吧?也许可以用正则表达式来实现,这是我还在努力掌握的技能。

谢谢!


6
这个问题似乎与代码审核有关,不符合主题。建议您到 http://codereview.stackexchange.com/ 提问。 - Ash Burlaczenko
单个示例不足以编写模式。当您仅提供单个示例时,没有合理的方法编写可在实际数据上运行的正则表达式。 - nhahtdh
4个回答

6
您可以使用这种模式。
^(\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

4
为了上帝的爱,请解释一下,以便我们可以学习? - Kick Buttowski
哦,很酷,你能提供更多关于它的信息吗?因为当我使用分割函数并将你的正则表达式放在里面时,它会给我整个字符串。顺便说一下,另一个人复制并粘贴了你的答案。 - Kick Buttowski
@KickButtowski,没问题。 - alpha bravo
@if循环,我更喜欢这个格式 - alpha bravo
让我们在聊天室继续这个讨论:(http://chat.stackoverflow.com/rooms/63972/discussion-between-kick-buttowski-and-alpha-bravo)。 - Kick Buttowski
显示剩余2条评论

4
这个正则表达式将返回您需要的内容:^(\S+)\s(.*?)\sat\s(.*)$ 解释: ^ 断言该行的开头位置。 \S+ 匹配任何非空格字符。 \s 匹配任何空格字符。 .*? 匹配任何字符(不包括换行符)。 \s 再次匹配任何空格字符。 at 按字面意义匹配字符“at”(区分大小写)。 \s 再次匹配任何空格字符。 (.*)$ 匹配任何字符(不包括换行符),并断言该行的结尾位置。

0

只需在 item 上调用 .split() 方法即可简化操作。 将该数组存储在 String[] 中,然后硬编码您想要的索引到您返回的 ArrayList 中。String.concat() 方法可能也会有所帮助。


0
这是一段代码,用于生成您请求的String[]结果。使用其他答案中建议的正则表达式:

^(\S+)\s(.*?)\sat\s(.*)$ 通过用另一个反斜杠转义每个反斜杠来将其转换为Java字符串,因此在创建Pattern对象时它们会出现两次。

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

如果您的输入字符串不符合模式,则可能会抛出“java.lang.IllegalStateException:No match found”。或者,您可以检查mather.find()的返回值以确定兼容性。 - Rob Hoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接