(Common API) regular expressions and exercises related to the String class method

Regular expression rules match practice

Please write the string matching rules satisfy the following:

Rule: "[0-9] {6,12}"

The need to match the rule content: length . 6 bit to 12 is bit number.

The: use the data "123456789" match results to true ;

Using the data "12345" match result to false .

 

Rule: "1 [34578] [0-9] {9}"

The need to match the rule content: . 11 -bit phone number, the first 1 bit is 1 , the second 2 bits 3 , 4 , 5 , 7 , 8 one behind . 9 bits 0 to . 9 any number between .

The: use the data "12345678901" match result to false ;

Using the data "13312345678" match results to true .

 

Rule: "a * b"

The need to match the rule content: a plurality of a or zero, a has a back B ; B must be the last character.

The: use the data "aaaaab" match results to true ;

Using the data "abc" match result to false .

 

    1. String class relates to the regular expression method used

 

public boolean matches(String regex) //判断字符串是否匹配给定的规则
举例:校验qq号码.
	1: 要求必须是5-15位数字
	2: 0不能开头
代码演示:
	String qq = "604154942";
	String regex = "[1-9][0-9]{4,14}";
	boolean flag2 = qq.matches(regex);

举例:校验手机号码
	1:要求为11位数字
2:第1位为1,第2位为3、4、5、7、8中的一个,后面9位为0到9之间的任意数字。
代码演示:
	String phone = "18800022116";
	String regex = "1[34578][0-9]{9}";
	boolean flag = phone.matches(regex);

public String[] split(String regex)	 //根据给定正则表达式的匹配规则,拆分此字符串
举例:分割出字符串中的的数字
代码演示:
String s = "18-22-40-65";
	String regex = "-";
	String[] result = s.split(regex);
代码演示:
	String s = "18 22 40 65";
	String regex = " ";
	String[] result = s.split(regex);
	
//将符合规则的字符串内容,全部替换为新字符串
public String replaceAll(String regex,String replacement)
举例:把文字中的数字替换成*
代码演示:
	String s = "Hello12345World6789012";
	String regex = "[0-9]";
	String result = s.replaceAll(regex, "*");
package cn.learn.demo01;
/*
 *  实现正则规则和字符串进行匹配,使用到字符串类的方法
 *  String类三个和正则表达式相关的方法
 *    boolean matches(String 正则的规则)
 *    "abc".matches("[a]")  匹配成功返回true
 *    
 *    String[] split(String 正则的规则)
 *    "abc".split("a") 使用规则将字符串进行切割
 *     
 *    String replaceAll( String 正则规则,String 字符串)
 *    "abc0123".repalceAll("[\\d]","#")
 *    安装正则的规则,替换字符串
 */ 
public class RegexDemo {
	
}

Regular expressions exercises and related method of the String class

* A: 正则表达式练习和相关的String类方法
	* a: boolean matches(String 正则的规则)
		* "abc".matches("[a]")  
		* 匹配成功返回true
	* b: String[] split(String 正则的规则)
		* "abc".split("a")  
		* 使用规则将字符串进行切割
	* c: String replaceAll( String 正则规则,String 字符串)
		* "abc0123".repalceAll("[\\d]","#")	
		* 按照正则的规则,替换字符串

 

Released 2417 original articles · won praise 62 · Views 200,000 +

Guess you like

Origin blog.csdn.net/Leon_Jinhai_Sun/article/details/105174026