如何将某些短语拆分为一个字符串?

时间:2014-08-06 09:54:46

标签: regex string split match

我有一些搜索项目的字符串,我想将它们拆分成一个String数组。

示例:

String text = "java example \"this is a test\" hello world";

我想得到以下结果

result[0] = "java";
result[1] = "example";
result[2] = "\"this is a test\"";
result[3] = "hello";
result[4] = "world";

简而言之,我想结合text.split("")和text.split(" \""); 有一种简单的方法来编码吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以在String#split方法中使用此正则表达式:

(?=(([^\"]*\"){2})*[^\"]*$)\\s+

<强>代码:

String text = "java example \"this is a test\" hello world";
String[] tok = text.split("(?=(([^\"]*\"){2})*[^\"]*$)\\s+");
// print the array
System.out.println( Arrays.toString( arr ) );

<强>输出:

[java, example, "this is a test", hello, world]

答案 1 :(得分:1)

此正则表达式应与(\\".+?\\")|([^\s]+)

匹配

它匹配\"内的任何内容,包括\"或单个单词。

点击此处查看结果:http://www.regexr.com/399a4

答案 2 :(得分:1)

我觉得你有点困惑,你的代码中有错误! 编写字符串应该是:

String text = "java example \"this is a test\" hello world";

变量text的值将是:

java example "this is a test" hello world

我宁愿假设您要将其提取到以下数组中:

result[0] = "java";
result[1] = "example";
result[2] = "\"this is a test\"";
result[3] = "hello";
result[4] = "world";

您可以使用正则表达式执行此操作,例如:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Example {

    public static void main(String[] args) {

        String data = "java example \"this is a test\" hello world";

        Pattern p = Pattern.compile("((?:\"[a-z\\s]+\")|[a-z]+)");
        Matcher m = p.matcher(data);

        List<String> lst = new ArrayList<String>();
        while(m.find()) {
            lst.add(m.group(1));
        }

        String[] result= new String[lst.size()];
        result = lst.toArray(results);

        for(String s: result) {
            System.out.println(s);
        }
    }
}

正则表达式((?:\"[a-z\\s]+\")|[a-z]+)将匹配: 1)字符序列az或双引号之间的空格 2)字符序列az

然后,我们使用m.find

提取这些匹配项
相关问题