我需要删除文件上的标点符号,保持重音字符
我试过这段代码,但不能像我那样工作。

Expectation: input=> ’'qwe..,rty ‘èeéò’“ ”o" "à     output=> qwertyèeéòoà

Effective result: input=> ’'qwe..,rty ‘èeéò’“ ”o" "à   output=>’qwerty ‘èeéò’“ ”o" "à

我无法删除 ’“” 符号和其他这些符号

注意:Eclipsefiletext.txt 设置为 UTF-8

谢谢
import java.io.*;
import java.util.Scanner;

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

    File file = new File("filetext.txt");

    try {
        Scanner filescanner = new Scanner(file);
        while (filescanner.hasNextLine()) {

            String line = filescanner.nextLine();
            line=line.replaceAll ("\\p{Punct}", "");

            System.out.println(line);
        }
    }
    catch(FileNotFoundException e) {
        System.err.println(file +" FileNotFound");
    }
    }
}

最佳答案

默认情况下,正则表达式 \p{Punct} 仅匹配 US-ASCII 标点符号,除非您启用 Unicode 字符类。这意味着您编写的代码只会删除这些字符:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

如果您想匹配 Unicode Consortium 归类为标点的所有内容,请尝试改用 \p{IsPunctuation},它始终检查 Unicode 字符属性并匹配示例中的所有标点(以及更多!)。

要替换空格和标点符号,就像在您的示例中一样,您可以使用:
             
        line = line.replaceAll("\\p{IsPunctuation}|\\p{IsWhite_Space}", "");
             

关于Java 删除字符串上的标点符号(还有 ' “” 和所有这些)维护重音字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47366788/

10-12 12:47
查看更多