Skip substring in String.Contains in Java

Viewed 68

For a given string

String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";

How can we check if welcomeMessage contains "Welcome, you have notification" substring by escaping name variable as name variable keeps on changing?

I want to achieve

welcomeMessage.contains("Welcome, You have notification!"); //to return true

What would be the best way to skip name variable?

3 Answers

String#startsWith & endsWith

The String class provides specific methods:

Example:

boolean containsPhrases = 
    message.startsWith( "Welcome" )
    &&
    message.endsWith( ", You have notification!" )
;

very simple

String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
            System.out.println(welcomeMessage + " matches " + welcomeMessage.matches("Welcome.+You have notification!"));

With matches on a regular expression. There are some special regex characters that need to be escaped with a backslash, twice \\ in a regex.

welcomeMessage.matches("Welcome .*, you have notification\\!");

.* stands for . = any character without line breaks, and * = repeat the previous 0 or more times. So any string.

Related