メールアドレスの仕様
https://tools.ietf.org/html/rfc5322#page-17
以下抜粋
—-
An addr-spec is a specific Internet identifier that contains a
locally interpreted string followed by the at-sign character (“@”,
ASCII value 64) followed by an Internet domain. The locally
interpreted string is either a quoted-string or a dot-atom. If the
string can be represented as a dot-atom (that is, it contains no
characters other than atext characters or “.” surrounded by atext
characters), then the dot-atom form SHOULD be used and the quoted-
string form SHOULD NOT be used. Comments and folding white space
SHOULD NOT be used around the “@” in the addr-spec.
addr-spec = local-part “@” domain
local-part = dot-atom / quoted-string / obs-local-part
domain = dot-atom / domain-literal / obs-domain
domain-literal = [CFWS] “[” *([FWS] dtext) [FWS] “]” [CFWS]
dtext = %d33-90 / ; Printable US-ASCII
%d94-126 / ; characters not including
obs-dtext ; “[“, “]”, or “\”
——-
使えるのは、半角英数字か、「!#$%&’*+-/=?^_`{|}~」
で、正規表現で書くと、
^[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+(\.[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+)*@[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+(\.[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+)*$
実際に試してみる。
import java.util.regex.Matcher; import java.util.regex.Pattern; class Playground { public static void main(String[ ] args) { String str = "hogehogehoge.jp"; Pattern p = Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$"); Matcher m = p.matcher(str); if(m.find() == true){ System.out.println("OK"); } else{ System.out.println("NG"); } } }
NGとなる。
メールアドレスの判定をする。
public void getScore(View view){ // edittextを取得 EditText fEditText = (EditText) findViewById(R.id.firstnEditText); EditText lEditText = (EditText) findViewById(R.id.lastnEditText); EditText pEditText = (EditText) findViewById(R.id.phoneEditText); EditText mEditText = (EditText) findViewById(R.id.mailEditText); // edittextの中身を取得 String firstName = fEditText.getText().toString().trim(); String lastName = lEditText.getText().toString().trim(); String myPhone = pEditText.getText().toString().trim(); String myMail = mEditText.getText().toString().trim(); Pattern p = Pattern.compile("^[0-9\\-]+"); Matcher m = p.matcher(myPhone); Pattern mp = Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\\\.[a-zA-Z0-9-]+)*$"); Matcher mm = mp.matcher(myMail); // 中身を観て条件分岐 if (firstName.equals("")){ fEditText.setError("Please enter your first name!"); } else if(lastName.equals("")){ lEditText.setError("Please enter your last name!"); } else if(myPhone.equals("") || m.find() == false){ pEditText.setError("Please enter your phone number!"); }else if(myMail.equals("") || mm.find() == false){ mEditText.setError("Please enter your valid email"); } else { Intent intent = new Intent(this, MyResult.class); intent.putExtra(EXTRA_MYNAME, firstName); startActivity(intent); } }