对于给定的字符串
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
我们如何检查welcomeMessage是否包含";欢迎,您收到通知"通过转义名称变量的子字符串,因为名称变量不断更改?
我想实现
welcomeMessage.contains("Welcome, You have notification!"); //to return true
跳过名称变量的最佳方式是什么?
String#startsWith
&endsWith
String
类提供了特定的方法:
startsWith
endsWith
示例:
boolean containsPhrases =
message.startsWith( "Welcome" )
&&
message.endsWith( ", You have notification!" )
;
非常简单的
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
System.out.println(welcomeMessage + " matches " + welcomeMessage.matches("Welcome.+You have notification!"));
在正则表达式上使用matches
。有些特殊的正则表达式字符需要用反斜杠转义,反斜杠是正则表达式中\
的两倍。
welcomeMessage.matches("Welcome .*, you have notification\!");
.*
代表.
=没有换行符的任何字符,*
=重复前0次或更多次。所以任何字符串。