新发现:原来java正则表达式不写^和$也可以运行

最近用了好多正则表达式,都是循规蹈矩的在前面加上^在后面加上$

像这个样子"^[.]\\S+$",但实际上我在eclipse和editplus下都试了一下,不加前缀和后缀也是可以的。

代码如下

 

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Test1 
{
	public static void main(String[] args) 
	{
		String str="asdf		dsgsdf";
		String regx="[\\w]+[\\s]+[\\w]+";
		Pattern pat=Pattern.compile(regx);
		Matcher mat=pat.matcher(str);
		boolean bool=mat.matches();
		//String end=mat.replaceAll("");
		System.out.println(bool);
		
	}
}

运行结果是true。

 

这样写的话,运行也是true

 

class Test1 
{
	public static void main(String[] args) 
	{
		String str="asdf		dsgsdf";
		String regx="\\w+\\s+\\w+";
		Pattern pat=Pattern.compile(regx);
		Matcher mat=pat.matcher(str);
		boolean bool=mat.matches();
		//String end=mat.replaceAll("");
		System.out.println(bool);
		
	}
}

所以,在以上这种情况下,不加[ ]和()是没有任何问题的。当然,加上也是没有问题的。。

 

至于为啥都要加两个反斜线\\,首先,\w匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。

单纯的\w,java是识别不出这个转义的,反斜线\本身需要再转义一下,这样java就能识别出这个转义序列了。

所以,在java中必须要写成\\w,\\s等。


 

posted on 2013-08-01 18:51  you Richer  阅读(388)  评论(0编辑  收藏  举报