Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法使用Java和正则表达式打印文件中的单词_Java_Regex - Fatal编程技术网

无法使用Java和正则表达式打印文件中的单词

无法使用Java和正则表达式打印文件中的单词,java,regex,Java,Regex,我试图扫描一个文本文件,并使用正则表达式只打印出包含字母的字符串 当我使用正则表达式时,我当前的代码总是返回false import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class DocumentReader { public static void main(String[] args) throws FileNotFoundException {

我试图扫描一个文本文件,并使用正则表达式只打印出包含字母的字符串

当我使用正则表达式时,我当前的代码总是返回false

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class DocumentReader {
    public static void main(String[] args) throws FileNotFoundException {

        File inputFile = new File("document.txt"); // document
        Scanner in = new Scanner(inputFile);            

        while (in.hasNext()){

            String input = in.next();
            input.matches("([^a-zA-Z])");
            System.out.println(input.matches("[^a-zA-Z]"));
            System.out.println(input);


            //if text matches regex, print text
            if (input.matches("[^a-zA-Z]")){
            System.out.println(input);
            }
        }

    }

}

问题:
[^a-zA-Z]
平均匹配单个非字母字符

由于要匹配包含字母的
请使用

  • [a-zA-Z]+
    一个或多个字母表,如
    []
代码:

    File inputFile = new File("document.txt"); // document
    Scanner in = new Scanner(inputFile);            

    while (in.hasNext()){

        String input = in.next();
        //input.matches("([^a-zA-Z])"); not required
        System.out.println(input.matches("[a-zA-Z]+")+"\n"+input);

        //if text matches regex, print text
        if (input.matches("[a-zA-Z]+")){
            System.out.println(input);
        }
演示

console.log(/^[a-zA-Z]+$/.test('abcd');

console.log(/^[a-zA-Z]+$/.test(“%s”);//忽略^$,默认情况下匹配添加它
您的意思是
[a-zA-Z]+