2

So what I am tasked to do is check if an email has a specific form.It has to be itxxxxxx@uom.edu.gr, where the x's can be whatever but the rest is a must.

If the rest is slightly different, I must print that this user is not accepted. I have no idea how to do that. I have written no code because I do not know how to tackle this problem.

pleft
  • 7,567
  • 2
  • 21
  • 45
  • Try to use regular expression. – Pein Nov 21 '16 at 13:39
  • Possible duplicate of [How to check if a String contains another String in a case insensitive manner in Java?](http://stackoverflow.com/questions/86780/how-to-check-if-a-string-contains-another-string-in-a-case-insensitive-manner-in) – Aleksandr Podkutin Nov 21 '16 at 13:39
  • Take a look at the indexOf method of the [String](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) class. – Gilbert Le Blanc Nov 21 '16 at 13:40
  • I think the regular expression solution in the answer is nice. If for some reason you don’t want to use it, you may look into `String.startsWith()` and `String.endsWith()`. – Ole V.V. Nov 21 '16 at 14:55

2 Answers2

4

You can use a regular expression.

A pattern that matches your input is: ^it\w*@uom.edu.gr. the \w* means

Zero or more of any word character (letter, number, underscore)

If you want to include more symbols e.g. "." but to exclude the "@" for obvious reasons you can change the pattern to use [^@]* which means

Zero or more of any single character excluding the "@".

So the pattern becomes: ^it[^@]*@uom.edu.gr

Use any of the two suits your needs.

Example code:

Pattern p = Pattern.compile("^it\\w*@uom.edu.gr");
Matcher m = p.matcher("itxxxxxx@uom.edu.gr");
boolean b = m.matches();

The above can be expanded as per you have been requested, e.g.:

public static void main(String[] args)throws Exception{

    String email = "itxxxxxx@uom.edu.gr";

    Pattern p = Pattern.compile("^it\\w*@uom.edu.gr");
    Matcher m = p.matcher(email);
    boolean b = m.matches();
    if(b) {
        System.out.println("Valid email");
    } else {
        System.out.println("Invalid email.");
    }

}
pleft
  • 7,567
  • 2
  • 21
  • 45
  • 1
    This is the right solution for the job. A detail, strictly speaking `\w*` doesn’t match “whatever”, only a-zA-Z_0-9. It may be good enough, or you may want to accept more characters depending on your knowledge of the email addresses. – Ole V.V. Nov 21 '16 at 14:01
  • @OleV.V. You are correct thanks for pointing it out,a better pattern would be: `^it[^@]*@uom.edu.gr` – pleft Nov 21 '16 at 14:09
1

Use startsWith and endsWith

String var = "itxxxxxx@end.com";
if(var.startsWith("it") && var.endsWith("end.com")){
    // your code
}
else {
   // String do not start with it or it does not end end.com
}
RobertS
  • 135
  • 1
  • 11