具有多个空格的正则表达式

时间:2017-06-23 10:07:22

标签: java regex string split

package stringsplit;

public class StringSplit {

    public static void main(String[] args) {
        String s = "hello world we are anonymous ";
        String[] s3 = s.split("\\s",2);
        for(String temp:s3){  
            System.out.println(temp);  
        }  
    }        

}

O / P:

hello 
world we are anonymous

上面的代码在1个空格字符后将我的字符串拆分为两部分 编译器遇到了。我然后介绍了' \\ s +' 以便拆分后 获得2个空格字符

o / p:

hello world
we are anonymous

但它没有用。谢谢你的高级指导。

3 个答案:

答案 0 :(得分:1)

根据javadoc字符串split(regex)split(regex, limit)按预期工作。根据您尝试实现的结果,您可以使用以下内容:

String s = "hello   world we are anonymous";
String[] s1 = s.split("\\s",2); //result is ["Hello", "  world we are anonymous"]
String[] s2 = s.split("\\s+",2); //result is ["Hello", "world we are anonymous"]
String[] s3 = s.split("\\s+",3); //result is ["Hello", "world", "we are anonymous"]
String[] s4 = s.split("\\s+"); //result is ["Hello", "world", "we", "are", "anonymous"]

答案 1 :(得分:0)

您可以使用String::indexof解决问题:

String s = "hello world we are anonymous ";
s = s.replaceAll("\\s+", " ").trim();//----------------------------------------------(0)
String s1 = s.substring(0, s.indexOf(" ", s.indexOf(" ") + 1));//--------------------(1)
String s2 = s.substring(s.indexOf(" ", s.indexOf(" ") + 1) + 1, s.length() - 1);//---(2)

(0) - 只是为了确保你在单词之间没有多个空格 (1) - 从0到第二个空间获取第一部分
(2) - 从第二个空格到字符串末尾的第二部分

<强>输出

hello world
we are anonymous

答案 2 :(得分:0)

阅读Split doc“限制参数控制图案的应用次数”,因此您不能通过拆分来实现它。
因此,如果你想在2个空格后分​​割,你必须写:

String s = "hello world we are anonymous ";
int firstSpace = s.indexOf(' ')+1;
int secondSpace = s.indexOf(' ', firstSpace)+1;
String part1 = s.substring(0, secondSpace);
String part2 = s.substring(secondSpace, s.length());
System.out.println(part1); // return "hello world"
System.out.println(part2); // return "we are anonymous "
相关问题