Java正则表达式是什么鬼?我有没有完全误解正则表达式的文档?

3
System.out.println("a".matches("^[A-Za-z]+"));
System.out.println("a ".matches("^[A-Za-z]+"));

这给我带来了:
true
false

你好!就我目前的理解,“[A-Za-z]” 包含了所有大小写的字母,而“+”表示一个或多个,因此在这个宇宙里至少看起来是可以工作的...

具体细节如下:

操作系统:Mac OS X 10.8.4

$ java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-11M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)

也许是因为我写perl写得太久了,所以java的正则表达式系统有点像但又不完全一样?不确定。
3个回答

7

String#matches()测试this字符串是否与整个模式匹配。让我们走进JavaDoc的世界:

String#matches(String)

告诉我们这个字符串是否与给定的正则表达式匹配。

调用此方法的形式为str.matches(regex)产生的结果与表达式完全相同

Pattern.matches(regex, str)

所以让我们来追踪它:

Pattern#matches(String regex, CharSequence input)

Compiles the given regular expression and attempts to match the given input against it.

An invocation of this convenience method of the form

Pattern.matches(regex, input);

behaves in exactly the same way as the expression

Pattern.compile(regex).matcher(input).matches()

最后一步:

Matcher#matches()

尝试将整个区域与模式进行匹配。

就是这样。这当然不是从JavaDoc中的String#matches(String)显而易见的。解决方案,当然是使用一种不坚持将模式与整个字符串匹配的方法。


嗯,我感觉还好。你会认为String类会得到一些使用,文档可能会在这方面有所帮助。哦,算了。 :-) - Ray Kiddy

2
System.out.println("a".matches("^[A-Za-z]+"));   //No space after "a" hence returning true
System.out.println("a ".matches("^[A-Za-z]+"));   //One space after "a" hence returning false

如果您想包含空格字符,请将第二个字符更改为“-”:

System.out.println("a ".matches("^[A-Za-z ]+")); 

1
你的正则表达式中没有空格,因此第二个返回 false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接