2014-10-30 48 views
3

第一篇文章。对人好点?Java:将两个不同点的字符串拆分为3个部分

学习Java。

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

我想这个字符串拆分为String[]ArrayList<String>分裂“的”所以我String[]"1""Book on wombats" 3串第一空间和周围的词串"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; 
    } 

所以这个工作得很好,BU当然,有一种更优雅的方式?也许与正则表达式,这是我仍然试图得到很好的处理。

谢谢!

+6

这个问题似乎是脱离主题,因为它是关于审查您的代码。请尝试在此处询问,http://codereview.stackexchange.com/。 – 2014-10-30 22:41:28

+0

单个示例没有足够的信息来编写模式。当你只提供一个例子时,没有合理的方法来编写一个适用于实际数据的正则表达式。 – nhahtdh 2014-10-31 02:50:31

回答

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
+3

为了爱上帝,解释一下,我们可以学习吗? – 2014-10-30 22:43:15

+0

你有使用拆分功能吗? – 2014-10-30 22:49:17

+0

我用过捕捉组 – 2014-10-30 22:52:29

0

那么它会通过只是在项目调用.split()更简单。 将该数组存储在String []中,然后硬编码将所需的String []的索引导入到您要返回的ArrayList中。 String.concat()方法也可能有帮助。

4

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

说明:

^断言位置在一行的开始。

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

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

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

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

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

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

(.*)$将匹配任何字符(除了换行符),并断言行结束的位置。

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

也可能会注意到如果您的输入字符串不适合该模式,则会抛出“java.lang.IllegalStateException:找不到匹配项”。或者你可以检查'mather.find()'的返回值来确定兼容性 – area5one 2014-10-31 01:08:32

相关问题