简体   繁体   English

如何用Java中的空字符串替换á字符?

[英]How to replace á character with empty string in Java?

I am parsing CSV file, there I encounter special characters like á .我正在解析 CSV 文件,在那里我遇到了像á这样的特殊字符。

String line = scanner.nextLine();

Can any one help me to remove á and corrupted characters from the string line.任何人都可以帮助我从字符串行中删除á和损坏的字符。 I tried the following我尝试了以下

line.replaceAll("[^a-zA-Z0-9]+","");

but it replacing : , / [ ] symbols.但它取代了: , / [ ]符号。

 inputStream = filePart.getInputStream();
 Scanner scanner = new Scanner(inputStream);
 while (scanner.hasNextLine()) {
     String line = scanner.nextLine();
     System.out.println("Line : " + line.trim());
     String[] fields = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
     for (int i = fields.length - 1; i >= 0; i--) {
         System.out.println(i + " " + fields[i].replaceAll("[á]", ""));
     }

Why not just replace a positive character class containing the accented character(s):为什么不替换包含重音字符的正字符类:

String input = "hablá";
input = input.replaceAll("[á]", "");
System.out.println(input);

Or或者

input = input.replaceAll("[\\u00e1]", "");

Output:输出:

habl

Demo演示

Add the characters you don't want stripped out to your regex pattern match.将您不想剥离的字符添加到正则表达式模式匹配中。

eg例如

[^a-zA-Z0-9$\/\]\[\:\,]+

Will match az, AZ, 0-9, /, \\, ], [, :, ,, Don't forget to escape special characters in the pattern with a \\会匹配 az, AZ, 0-9, /, \\, ], [, :, ,, 不要忘记用\\转义模式中的特殊字符

Also you can use https://regex101.com/ to check the validity of any regex you create.您也可以使用https://regex101.com/检查您创建的任何正则表达式的有效性。

You can use the replace method as shown below:您可以使用如下所示的替换方法:

line = line.replace("á","");

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM