【问题标题】:Java: Splitting a String at two different points into 3 parts [closed]Java:将两个不同点的字符串拆分为 3 个部分 [关闭]
【发布时间】:2014-10-30 22:38:05
【问题描述】:

第一次发帖。好看吗?

学习 Java。

我有一个字符串对象"1 Book on wombats at 12.99"

我想将此字符串拆分为 String[]ArrayList<String> 在第一个空格和单词“ at ”周围拆分字符串,因此我的 String[] 有 3 个字符串 "1" "Book on wombats" @ 987654328@

我目前的解决方案是:

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

所以这很好用,但肯定有更优雅的方法吗?也许使用正则表达式,这是我仍在努力掌握的东西。

谢谢!

【问题讨论】:

  • 这个问题似乎是题外话,因为它是关于审查你的代码。尝试在这里询问,codereview.stackexchange.com
  • 单个示例信息不足以编写模式。当您只提供一个示例时,没有合理的方法可以编写适用于实际数据的正则表达式。

标签: java regex string split


【解决方案1】:

你可以使用这个模式

^(\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

【讨论】:

  • 看在上帝的份上,解释一下让我们学习?
  • 你使用了分割功能吗?
  • 我使用了捕获组
  • 很酷,你能提供更多信息吗?因为当我使用 split 函数并将您的正则表达式放入其中时,它给了我整个字符串。顺便说一句,其他人复制并粘贴了您的答案
  • @KickButtowski,没关系
【解决方案2】:

此正则表达式将返回您需要的内容:^(\S+)\s(.*?)\sat\s(.*)$

说明:

^ 在行首断言位置。

\S+ 将匹配任何非空白字符。

\s 将匹配任何空白字符。

.*? 将匹配任何字符(换行符除外)。

\s 再次匹配任何空白字符。

at 与字符 at 逐字匹配(区分大小写)。

\s 再次匹配任何空白字符。

(.*)$ 将匹配任何字符(换行符除外),并在行尾断言位置。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      这里有一段代码可以得到您请求的 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()的返回值来确定兼容性
      猜你喜欢
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2015-10-31
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多