程序中的正则表达式不起作用

Regex expression in the program doesn't work

我正在编写一个程序,该程序将读取文本文件并在文本中包含既不是空格也不是单词字符的任何字符时抛出错误。正则表达式似乎是正确的,但它不起作用。

例如这些文本:

在控制台中显示没有错误

我也在 https://regexr.com/ 上检查了正则表达式

需要双 \,否则我会收到错误 Illegal escape character

import java.io.*;

public class DZ {
    public static void main(String[] args) throws IOException {
        try {
            System.out.println(method());
        } catch(Exception e){
            System.out.println(e);
        }
    }

    public static boolean compare(char wrt) {
        String str = "[^\s\w]";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == wrt) {
                return true;
            }
        }
        return false;
    }

    public static StringBuilder method() throws Exception {
        int data;

        FileReader fr = new FileReader("/Users/rachel_green/Documents/1.txt");
        StringBuilder str = new StringBuilder();
        while ((data = fr.read()) != -1) {
            if (compare((char)data)) {
                throw new Exception("Wrong file format");
            } else {
                str.append((char) data);
            }
        }

        return str;
    }
}

您正在将 Stringchar 进行比较,并且您正在迭代包含您的 RegEx 的字符串 - 这没有意义:

public static boolean compare(char wrt){
    String str = "[^\s\w]";
    for(int i=0;i<str.length();i++){ //why are you diong this?
        if(str.charAt(i) == wrt) //you are checking every char of the regex agains the input char!
            return true;
    }
    return false;
}

相反,您可以这样做:

public static boolean compare(char wrt){
    return (wrt + "").matches("[^\s\w]");
}

另外,第一次发现无效字符时停止读取文件可能是个好主意。否则,你检查每个 char 而不是整个文件内容(比如 content.matches(".*[^\s\w].*"))真的没有意义。只抛出一次异常并 break; 循环读取文件那么!

在上面的代码中,您正在为每个字符迭代,相反,您可以将输入文件中的每一行与模式匹配。

public static boolean compare(String wrt)
{
    Pattern regex = Pattern.compile("[^\s\w]");

    Matcher matcher = regex.matcher(wrt);
    return matcher.find();
}

public static StringBuilder method() throws Exception
{
    FileReader fr = new FileReader("/Users/rachel_green/Documents/1.txt");

    BufferedReader bR = new BufferedReader(fr);
    StringBuilder str = new StringBuilder();
    String line;
    while ((line = bR.readLine()) != null)
    {
        if (compare(line))
        {
            throw new Exception("Wrong file format");
        }
        else
        {
            str.append(line);
        }
    }
    return str;
}

希望对您有所帮助。