有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java分割正则表达式

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]);

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


共 (1) 个答案

  1. # 1 楼答案

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

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

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

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

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

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

    在这种情况下,您只需要转义[]

    更新:

    特殊角色的开头也有问题(比如你的例子^{)。您需要对其进行拆分,但它会在结果中生成一个空字符串。我不认为有一种方法可以在不生成拆分函数的情况下使用拆分函数,但可以通过在使用相同的正则表达式拆分之前删除第一个组来缓解它:

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