Java uses regular expressions to determine legitimate E-mail address

Java foundation using regular expressions judged legitimate E-mail address

Regular expressions are commonly used in the decision statement, for checking whether a string satisfies certain format.

Use regular expressions to determine whether the input variable legitimate E-mail address.

import java.util.Scanner;

public class Demo {
	public static void main(String[] args) {
		String address;
		Scanner input=new Scanner(System.in);
		System.out.println("请输入邮箱地址:");		//提示用户输入邮箱地址
		address=input.nextLine();
		String regex="\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";	//定义要匹配使用的E-mail使用的正则表达式
		if(address.matches(regex)) {	//判断字符串变量是否与正则表达式匹配
			System.out.println(address+"是合法的邮箱!");
		}else {
			System.out.println(address+"不是合法的邮箱!");
		}
	}		
}

The results are shown

Regular expression analysis:

E-mail is usually in the format of "[email protected]". Feature Summary Email address, the regular expression can be written "\\ w + @ \\ w + (\\. \\ w {2,3}) * \\. \\ w {2,3}" to match Email address. Character Set "\\ w" matches any character, symbol "+" represents a character may be one or more times, the expression "(\\. \\ w {2,3}) *" indicates shaped like ".com" string format may appear zero or more times. The last expression "\\. \\ w {2,3}" character is used to match the end of the E-mail address, such as "com".


Square brackets can be used from a plurality of characters in a regular expression element to represent a character, the character can be any element representative of a character in brackets.

[^ 456]: any character other than representatives of 4,5,6.

[Ar]: represents any letter of a ~ r.

[A-zA-Z]: may represent any of the English alphabet.

[Ae [gz]]: Representative a ~ e, a letter or any of g ~ z (and calculation).

[Ao && [def]]: represent letters d, e, f (cross operation).

[Ad && [^ bc]]: represent letters a, d (difference calculation).


Allowing regular expression defined modifier used to define the number of characters appearing element.

Limited modifier
Limited modifier significance Examples
0 or 1 A?
* 0 or more times A*
+ One or more times A+
{n} Just appear n times A{2}
{n,} Appears at least n times A{3,}
{n,m} N ~ m times appear A{2,6}

 

Published 35 original articles · won praise 5 · Views 871

Guess you like

Origin blog.csdn.net/m0_43443133/article/details/104504029