Java basic syntax — what is API — regular expression

regular expression

Is a regular expression that operates on string data

Rule: it is composed of some symbols, and each symbol represents a unique meaning.

In fact, these symbols correspond to a piece of code at the bottom. Providing external symbols simplifies the operation.

Disadvantages: you must learn these symbols first. If there are more symbols, the reading ability will be poor.

Common operations of regular expressions on strings

Match:

The matches method in the string class is used

Cutting:

The split method in the string class is used.

Replace:

The replaceall method in the string class is used.

obtain:

Get the content of the matching rule.

Use pattern to regular expression object

Use steps:

1. First compile the regular expression into a pattern object.

2. Get the matcher matcher object through the matcher method of the pattern object.

3. Through the method of matcher object, the regular rules are applied to the string for easy operation.

Examples

1. Check whether the email address is legal.

public class Test{
	public static void main(String[] args){
		checkMail();
	}
	/*
	 * 检查邮件地址是否合法
	 * 规则:
	 * 	12344@qq.com
	 * mahahd@163.com
	 * sdhas@sina.com
	 * woeidsf@yahoo.com.cn
		 * @:前   数字字母 _  个数不少于1个
	 * @:后  数字字母  个数不少于1个
	 * .:后面 字母
	 */
	public static void checkMail(){
		String email="absc123@sina.com";
		boolean b=email.matches("[a-zA-Z0-9]+@[a-z0-9]+(\\.[a-z]+)+");
		System.out.println(b);
	}
}

2. Cut string

public class Test{
	public static void main(String[] args) {
		splittest();
	
	}
	/*
	 * String 类方法 split 对字符串进行切割 192.168.106.25 按照 .点 切割字符串
	 */
	public static void splittest() {
		String ip = "192.168.106.25";
		String[] strArr = ip.split("\\.+");
		for (int i = 0; i < strArr.length; i++) {
			System.out.println(strArr[i]);
		}
	}

}

3. Replace

public class Test{
	public static void main(String[] args) {

		replaceAlltest();
	}
	/*
	 * "Hello12342WOrld70897"将所有的数组替换掉 String类方法replaceAll(正则规则,替换后的新字符串)
	 */
	public static void replaceAlltest() {
		String str = "Hello12342WOrld70897";
		str = str.replaceAll("[\\d]+","#");
		System.out.println(str);
	}

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>