删除字符串中的背靠背破折号和星号

时间:2014-11-13 17:13:46

标签: java

我在阅读文件并删除文件中的所有标点符号时遇到了一些问题。 以下是我目前的情况,我无法弄清楚为什么" ----"和" *****"仍会发生。

有人能指出我的方向,弄清楚我需要如何调整我的replaceAll(),以确保可以删除重复出现的标点符号吗?

public void analyzeFile(File filepath) {
    try {
        FileInputStream fStream = new FileInputStream(filepath);
        DataInputStream in = new DataInputStream(fStream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String textFile = "";
        String regex = "[a-zA-Z0-9\\s]";
        String putString = "";
        wordCount = 0;

        while ((textFile = br.readLine()) != null) {
            if (!textFile.equals("") && textFile.length() > 0) {
                String[] words = textFile.split(" ");
                wordCount += words.length;
                for (int i = 0; i < words.length; i++) {
                    putString = cleanString(regex, words[i]);
                    if(putString.length() > 0){
                        mapInterface.put(putString, 1);
                    }
                }
                putString = "";
            }
        }

        in.close();
    } catch (Exception e) {
        System.out.println("Error while attempting to read file: "
                + filepath + " " + e.getMessage());
    }
}

private String cleanString(String regex, String str){
    String newString = "";
    Pattern regexChecker = Pattern.compile(regex);
    Matcher regexMatcher = regexChecker.matcher(str);
    while(regexMatcher.find()){
        if(regexMatcher.group().length() != 0){
            newString += regexMatcher.group().toString();
        }
    }
    return newString;
}

1 个答案:

答案 0 :(得分:-1)

当然,您可以使用\w转义的字母数字字符?这将识别所有字母和数字,但不识别标点符号。

putString = words[i].replaceAll("[^\w]+", "");

这会将任何非单词字符替换为空字符串。

相关问题