【问题标题】:question related to split() from regex java与正则表达式 java 中的 split() 相关的问题
【发布时间】:2020-06-19 14:28:05
【问题描述】:

导入 java.io.; 导入 java.util.;

公共类解决方案{

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    String s1=s.replaceAll("[^a-zA-Z]"," ").trim();
    String[] word=s1.split("\\s+");
    System.out.println(word.length);
    for(String item : word)
    {
        System.out.println(item);
    }
    scan.close();
}

i/p:-任何不带 alpha-bates 的字符串(例如 @##%&*%^$!@#$% ^#@%^ %$#@$ ) o/p:-1

上面是我的代码,但是当我运行它时,如果我输入一些没有 a-z 或 A-Z 的字符串,例如 ';3#$@%^32' 它会返回一个空格,如果我调用array.length 它返回 1 作为大小 任何人都可以帮我解决它。我怎么能在最后得到空(甚至没有空格)数组? 提前致谢。

【问题讨论】:

  • @Turo 这正是 OP 所做的。
  • String.split() 总是返回至少一个元素。如果你想在某些情况下有一个空数组,你需要自己处理这些情况。例如。 `if(s1.isEmpty()) word = new String[0];

标签: java regex split


【解决方案1】:

嘿,如果您想检查 @$%512 之类的内容是否不在文本中,您可以使用它。 如果这不是你要找的东西,试着用另一种方式说出来

    Scanner scan = new Scanner(System.in);

    String s = scan.nextLine();
    String regex = "^[a-zA-Z]+$";

    Pattern pattern = Pattern.compile(regex);

    Matcher matcher = pattern.matcher(s);

    System.out.println(matcher.matches());

    scan.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多