0

I am new to java. I am practicing String methods currently. I wanted to check if the email contains "gmail.com" or not. This is the code I came up with

        System.out.println(domain.matches(".*gmail.com(.*)"));

but dot(.) here means any character so even if i pass the string as "xyz@gmailpcom" it will return true. Basically I want to check dot(.) in the string without considering it as regular expression.

2 Answers2

5

If you just want to check whether it contains gmail.com, then just use contains:

System.out.println(domain.contains("gmail.com"));

If at a later stage you want to use a regular expression but escape a dot, do that with a backslash in the regular expression, which needs to be escaped again for use in a Java string literal:

domain.matches(".*gmail\\.com(.*)")
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

you can also check it bu checking the indexOf or lastIndexOf:

System.out.println(domain.indexOf("gmail.com") != -1);

System.out.println(domain.lastIndexOf("gmail.com") != -1);
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36