Java 拆分正则表达式

Java Split regex

Given a string S, find the number of words in that string. For this problem a word is defined by a string of one or more English letters.

Note: Space or any of the special characters like ![,?.\_'@+] will act as a delimiter.

Input Format: The string will only contain lower case English letters, upper case English letters, spaces, and these special characters: ![,?._'@+].

Output Format: On the first line, print the number of words in the string. The words don't need to be unique. Then, print each word in a separate line.

我的代码:

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    String regex = "( |!|[|,|?|.|_|'|@|+|]|\\)+";
    String[] arr = str.split(regex);
    
    System.out.println(arr.length);
    
    for(int i = 0; i < arr.length; i++)
        System.out.println(arr[i]);

当我提交代码时,它适用于超过一半的测试用例。我不知道测试用例是什么。我正在寻求有关墨菲定律的帮助。我实现的正则表达式在哪些情况下不起作用?

您没有在正则表达式中转义某些特殊字符。让我们从 [] 开始。由于您没有转义它们,因此部分 [|,|?|.|_|'|@|+|] 被视为一组字符 |,?._'@+。这意味着您的正则表达式不会在 [].

上拆分

例如 x..]y+[z 拆分为 x]y[z

您可以通过转义这些字符来解决这个问题。这将迫使你逃避更多的他们,你最终得到一个正确的定义:

String regex = "( |!|\[|,|\?|\.|_|'|@|\+|\])+";

请注意,您可以使用一个集来代替定义替代项,这将使您的正则表达式更易于阅读:

String regex = "[!\[,?._'@+\].]+";

在这种情况下你只需要转义[].

更新:

前导特殊字符也存在问题(如您的示例 ".Hi?there[broski.]@@@@@")。您需要对其进行拆分,但它会在结果中产生一个空字符串。我不认为有一种方法可以在不生成它的情况下使用拆分函数,但是您可以通过在使用相同的正则表达式拆分之前删除第一组来减轻它:

String[] arr = str.replaceFirst(regex, "").split(regex);