Java 正则表达式-是否有必要使用^&;美元在匹配项()的正则表达式字符串中?
输出:Java 正则表达式-是否有必要使用^&;美元在匹配项()的正则表达式字符串中?,java,regex,Java,Regex,输出: String regex1 = "^dog$"; String regex2 = "dog"; Pattern pattern1 = Pattern.compile(regex1); Pattern pattern2 = Pattern.compile(regex2); Matcher matcher1 = pattern1.matcher("dog"); Matcher matcher2 = pattern1.matcher("doggie"); Matcher matcher3 =
String regex1 = "^dog$";
String regex2 = "dog";
Pattern pattern1 = Pattern.compile(regex1);
Pattern pattern2 = Pattern.compile(regex2);
Matcher matcher1 = pattern1.matcher("dog");
Matcher matcher2 = pattern1.matcher("doggie");
Matcher matcher3 = pattern2.matcher("dog");
Matcher matcher4 = pattern2.matcher("doggie");
System.out.println(matcher1.matches());
System.out.println(matcher2.matches());
System.out.println(matcher3.matches());
System.out.println(matcher4.matches());
我建议你参考:
尝试根据图案匹配整个区域
因此,使用
^
和$
确实是多余的。第一个和第二个正则表达式应该完全相同:
true
false
true
false
表示开始(^)和结束($)之间的字符串狗
意思是一样的。
如果要匹配
小狗
,请使用一些通配符,如?
或*
或g+
,等等。您已经知道答案,如您在此处列出的示例所示。
String regex1 = "^dog$";
String regex2 = "dog";