java中的正则表达式[“0-9”]问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19141661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:28:05  来源:igfitidea点击:

Regular expression["0-9"] issue in java

javaregexstringfile-io

提问by Anish

I have a text file as follows:

我有一个文本文件如下:



Title
XYZ
Id name
1  abc
2  pqr
3  xyz


I need to read the content starting with the integer value and I used the regular expression as in the following code.

我需要读取以整数值开头的内容,并使用了以下代码中的正则表达式。

public static void main(String[] args) throws FileNotFoundException {
   FileInputStream file= new FileInputStream("C:\Users\ap\Downloads\sample1.txt"); 
   Scanner scanner = new Scanner(file);
          while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("[0-9]")) {
                System.out.println("Line: "+line);
            }
           }
}

The above code can't detect the lines starting with integers. However, it works fine if single integer values are passed to startsWith()function. Please suggest, where I went wrong.

上面的代码无法检测以整数开头的行。但是,如果将单个整数值传递给startsWith()函数,它就可以正常工作。请建议,我哪里出错了。

采纳答案by Rohit Jain

String#startsWith(String)method doesn't take regex. It takes a string literal.

String#startsWith(String)方法不使用正则表达式。它需要一个字符串文字。

To check the first character is digit or not, you can get the character at index 0 using String#charAt(int index)method. And then test that character is digit or not using Character#isDigit(char)method:

要检查第一个字符是否为数字,您可以使用String#charAt(int index)方法获取索引 0 处的字符。然后使用Character#isDigit(char)方法测试该字符是否为数字:

if (Character.isDigit(line.charAt(0)) {
    System.out.println(line);
}

回答by Fabio

For regex you can use the "matches" method, like this:

对于正则表达式,您可以使用“匹配”方法,如下所示:

line.matches("^[0-9].*")