[英]Remove Special char from the string
嗨,大家好,我尝试从字符串中删除特殊的字符和数字,但一切正常,但是字符'h'已打印在前缀和后缀中,我不知道为什么它会打印出错误提示我...
String str = "<h1>Hi buddy!!you @ $ did a Great job . <h1>";
String str1 = str.replaceAll("[^\\p{L}\\p{M}]", " ");
System.out.println(str1);
我的预期输出
Hi buddy you did a Great job
但是我得到了
h Hi buddy you did a Great job h
如评论中所述,在删除除字母和标记之外的所有内容之前,您应该使用HTML解析器摆脱标记。
如果您坚持使用正则表达式删除标签,则可以改为:
String str1 = str.replaceall("<[^>]*>", "").replaceAll("[^\\p{L}\\p{M}]", " ");
即删除标签之前...
这两个h
来自输入源中的<h1>
标记:
<h1>Hi buddy!!you @ $ did a Great job . <h1>
^ ^
| |
+ ------------- Here and here ----------+
如果您不想看到它们,请在调用replaceAll
之前找到这些标记并删除它们。 一种快速的方法是在单独的replaceAll
调用中应用"<\\\\p{Alnum}+>"
正则表达式。 可以进行实验学习,但是对于生产来说太脏了。 如果需要可靠地执行此操作,请获取HTML解析器以删除标签。
使用此代码。 会的..
String str = "<h1>Hi buddy!!you @ $ did a Great job . <h1>";
String str1 = str.replaceAll("<[^>]+>", "");
String str2 = str1.replaceAll("[^\\p{L}\\p{M}]", " ");
System.out.println(str2);
如果发现一个以上的连续空格到一个空格,将删除该标签,并删除所有特殊字符。
String str = "<h1>Hi buddy!!you @ $ did a Great job . <h1>";
// String str1 = str.replaceAll("[^\\p{L}\\p{M}]", " ");
String str1 = str.replaceAll("<[^>]+>", "").replaceAll("[^\\p{L}\\p{M}]", "
").replaceAll("\\s+", " ");
System.out.println(str1);
输出:
Hi buddy you did a Great job
试试这个程序就可以了
public class StringFunction{
public static void main(String args[])
{
String str = "<h1>Hi buddy!!you @ $ did a Great job . <h1>";
System.out.println(str.replaceAll("<[^>]+>", "").replaceAll("[^\\p{L}\\p{M}]", " "));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.