【问题标题】:How can I split certain phrase a String?如何将某些短语拆分为字符串?
【发布时间】:2014-08-06 09:54:46
【问题描述】:

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

例子:

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("\""); 有没有简单的编码方法?

谢谢!

【问题讨论】:

    标签: regex string split match


    【解决方案1】:

    您可以在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]
    

    【讨论】:

      【解决方案2】:

      这个正则表达式应该匹配(\\".+?\\")|([^\s]+)

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

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

      【讨论】:

        【解决方案3】:

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

        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提取这些匹配项

        【讨论】:

        • 谢谢。你是对的。我只是写了我的代码,没有在我的编译器上测试它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        相关资源
        最近更新 更多