第三行的职责是什么,(.*)
它是如何工作的?
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.matches("(.*)Tutorials(.*)"));
.matches()
是使用提供的正则表达式进行解析的调用Str
。
正则表达式或正则表达式是一种将字符串解析为组的方法。在提供的示例中,这匹配任何包含单词“Tutorials”的字符串。(.*)
简单的意思是“一组零个或多个任意字符”。
此页面是一个很好的正则表达式参考(用于非常基本的语法和示例)。
matches
将正则表达式字符串作为参数,(.*)
表示贪婪地捕获任何字符零次或多次
.*
表示一组零个或多个任意字符
在Regex
:
.
通配符:匹配任何单个字符,除了
\n
例如模式a.e
匹配ave
innave
和ate
inwater
*
匹配前一个元素零次或多次
for example pattern \d*\.\d
matches .0
, 19.9
, 219.9
There is no reason to put parentheses around the .*
, nor is there a reason to instantiate a String
if you've already got a literal String
. But worse is the fact that the matches()
method is out of place here.
What it does is greedily matching any character from the start to the end of a String. Then it backtracks until it finds "Tutorials"
, after which it will again match any characters (except newlines).
It's better and more clear to use the find method. The find method simply finds the first "Tutorials"
within the String, and you can remove the "(.*)"
parts from the pattern.
As a one liner for convenience:
System.out.printf("Return value : %b%n", Pattern.compile("Tutorials").matcher("Welcome to Tutorialspoint.com").find());