`

用正则表达式去掉多余的空格与标点符号 Java

阅读更多
转帖过来的 直接看程序吧
public class StringUtil {
	public void demo() {
		// String stringInfo =
		// "{infoNum='10' EdwardBlog='http://hi.baidu.com/Edwardworld'       topicLength='20'    titleShow='yes' EdwardMotto='I am a man,I am a true man!' /}";
		String stringInfo = "Madam,         I'm Adam";
		System.out.println("待处理的字符串:" + stringInfo);
		
		Pattern p = Pattern.compile("[.,\"\\?!:']");// 增加对应的标点
		Matcher m = p.matcher(stringInfo);
		
		String first = m.replaceAll(""); // 把英文标点符号替换成空,即去掉英文标点符号
		System.out.println("去掉英文标点符号后的字符串:" + first);
		
		p = Pattern.compile(" {2,}");// 去除多余空格
		m = p.matcher(first);
		String second = m.replaceAll(" ");
		System.out.println("去掉多余空格后的字符串" + second);// second为最终输出的字符串
		
		second = first.replace(" ", "");
		System.out.println("去掉所有空格:" + second);
	}
}
分享到:
评论
4 楼 RangerWolf 2013-07-06  
dingran 写道
谢谢,正好需要这个。
Pattern p = Pattern.compile("[.,\"\\?!:']");
这里面应该在多加些全角的符号就能过滤中文里面的标点符号了,现在只能用于英文



其实我不太懂正则表达式~
多谢指导!
3 楼 dingran 2013-04-13  
谢谢,正好需要这个。
Pattern p = Pattern.compile("[.,\"\\?!:']");
这里面应该在多加些全角的符号就能过滤中文里面的标点符号了,现在只能用于英文
2 楼 RangerWolf 2012-08-20  
确实是乱写的~~~~
不知道从哪里copy过来的~
1 楼 simpletrc 2012-07-16  
乱写什么啊!

相关推荐

Global site tag (gtag.js) - Google Analytics