Home > Back-end >  Skip substring in String.Contains in Java
Skip substring in String.Contains in Java

Time:09-09

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?

CodePudding user response:

String#startsWith & endsWith

The String class provides specific methods:

Example:

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

CodePudding user response:

very simple

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

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related