我是Java初学者,了解正则表达式的工作方式仍然非常复杂。我不知道如何创建一个正则表达式来检查并从字符串中删除一些特定的特殊字符。
“!@#$%¨& *()_- + = {[}]º| \,。:;?/°(我需要检查并从字符串中删除)
提前致谢
答案 0 :(得分:1)
我不知道这是一个好习惯,但它是否有效。
private String check(String answer) {
return answer.replaceAll("[!@#$%¨&*()_\\-+={\\[}\\]º|\\\\,.:;?/°]", "");
}
String answer = "Lore!m ips@um dol$or si%t amet, co¨nsectetur adi&piscing el*it. Mo(rbi pla)cerat, tu_rpis s_it am+et acc=umsan ve{nenatis, ma[gna r}isus ulla]mcorper an|te, ne\\c por,ttitor lac.us n:unc se;d el?it. Nul/la tristi°que posºuere felis, in ullamcorper sapien dignissim sit amet.";
Log.i("ans", check(answer));
Lorem ipsum dolor sit amet consectetur adipiscing elit Morbi placerat turpis
sit amet accumsan venenatis magna risus ullamcorper ante nec porttitor lacus
nunc sed elit Nulla tristique posuere felis in ullamcorper sapien dignissim
sit amet
答案 1 :(得分:1)
您可以使用正则表达式删除所有标点符号(\p{P}
)和符号(\p{S}
)和º
符号:
String result = s.replaceAll("[\\p{S}\\p{P}º]+", "");
或使用\p{Punct}
(One of !"#$%&'()*+,-./:;<=>?@[\]^_{|}~`
)
String result = s.replaceAll("[\\p{Punct}º]+", "");
查看Java demo:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String answer = "Lore!m ips@um dol$or si%t amet, co¨nsectetur adi&piscing el*it. Mo(rbi pla)cerat, tu_rpis s_it am+et acc=umsan ve{nenatis, ma[gna r}isus ulla]mcorper an|te, ne\\c por,ttitor lac.us n:unc se;d el?it. Nul/la tristi°que posºuere felis, in ullamcorper sapien dignissim sit amet.";
System.out.println(check(answer));
}
private static String check(String answer) {
return answer.replaceAll("[\\p{S}\\p{P}º]+", "");
}
}
输出:
Lorem ipsum dolor sit amet consectetur adipiscing elit Morbi placerat turpis sit amet accumsan venenatis magna risus ullamcorper ante nec porttitor lacus nunc sed elit Nulla tristique posuere felis in ullamcorper sapien dignissim sit amet