黑马程序员技术交流社区
标题:
正则表达式简单问题
[打印本页]
作者:
奥特曼爱小怪兽
时间:
2012-4-24 02:29
标题:
正则表达式简单问题
import java.util.regex.*;
public class RegexTest{
public static void main(String[] args){
String str1 = "RegexText";
String str2 = "TextRegex";
if(str1.matches("^Regex"))
System.out.println("第一个匹配.");
if(str2.matches("Regex$"))
System.out.println("第二个匹配.");
if(str1.matches("^Regex...."))
System.out.println("第三个匹配.");
}
}
复制代码
这段程序运行结果为什么只有第三个匹配上了。按照正则表达式的规则^Regex是用Regex开头。Regex$是用Regex结尾,第一个和第二个也应该匹配上啊。为何匹配不上呢。
作者:
黄秋
时间:
2012-4-24 05:35
刚看到你的问题,我差点也被你搞晕,后来试试,想起这不是find 方法,matches 方法是与整个串匹配。加上“.*”就匹配了,如 str1.matches("^Regex.*")。
作者:
王运科
时间:
2012-4-24 09:57
matches函数不是子串匹配,而是完全匹配。
如果想在母串中找字符,可以用indexOf。
如果用matches找字串,应该使用通配符。
主方法代码可以改为:
String str1 = "RegexText";
String str2 = "TextRegex";
if(str1.matches("^Regex.*"))
System.out.println("第一个匹配.");
if(str2.matches(".*Regex$"))
System.out.println("第二个匹配.");
if(str1.matches("^Regex...."))
System.out.println("第三个匹配.");
}
三个就全部匹配了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2