——-android培训java培训期待与您交流!———-
概述:
- 符合一定规则的表达式,用于专门操作字符串。
- 简化字符串书写和操作。
- 符号定义越多,正则越长,阅读性越差。
package com.sergio.Regex;
/**
* 正则表达式实例,校验qq数字。
* Created by Sergio on 2015-05-24.
*/
public class RegexDemo {
public static void main(String[] args) {
checkQQ();
}
public static void checkQQ() {
String qq = "123845";
String regex = "[1-9][0-9]{4,14}";
boolean flag = qq.matches(regex);
if (flag) {
System.out.println(qq + "格式正确");
} else {
System.out.println(qq + "格式正确");
}
}
}
匹配
- String的matches()方法可以用来匹配整串字符串,只要有一处不符合规则,就匹配结束返回false。
- 匹配常见规则有:

package com.sergio.Regex;
/**
* 匹配13xxx,15xxx,18xxx开头的手机号码
* Created by Sergio on 2015-05-24.
*/
public class TelCheckDemo {
public static void main(String[] args) {
String tel = "18992763318";
String reg = "1[358]\\d{9}";
System.out.println(tel.matches(reg));
}
}
切割
package com.sergio.Regex;
/**
* 切割
* Created by Sergio on 2015-05-25.
*/
public class SplitDemo {
public static void main(String[] args) {
splitString("zhangsan.lisi.wangwu", "\\,");
splitString("c:\\abc\\a.txt", "\\\\");
splitString("abccsfkksdfqquyiaaaau", "(.)\\1+");
}
public static void splitString(String str, String reg) {
String[] arr = str.split(reg);
for (String s : arr) {
System.out.println(s);
}
}
}
替换
- String的replaceAll()方法来做字符串替换。
package com.sergio.Regex;
/**
* 切割
* Created by Sergio on 2015-05-25.
*/
public class SplitDemo {
public static void main(String[] args) {
splitString("zhangsan.lisi.wangwu", "\\,");
splitString("c:\\abc\\a.txt", "\\\\");
splitString("abccsfkksdfqquyiaaaau", "(.)\\1+");
}
public static void splitString(String str, String reg) {
String[] arr = str.split(reg);
for (String s : arr) {
System.out.println(s);
}
}
}
获取
- 将字符串中的符合规则的字串取出。操作步骤:
- 将正则表达式封装成对象。
- 让正则对象和要操作的字符串相关联。
- 关联后,获取正则匹配引擎。
- 通过引擎对符合规则的字串进行操作,比如取出。
package com.sergio.Regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则表达式获取的功能步骤
* Created by Sergio on 2015-05-25.
*/
public class GetDemo {
public static void main(String[] args) {
getDemo();
}
public static void getDemo() {
String str = "ming tian jiu kai shi fang jia le !";
String reg = "\\b[a-z]{3}\\b";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
System.out.println(m.start() + "::" + m.end());
}
}
}
package com.sergio.Regex;
import java.util.TreeSet;
/**
* 将重复词的句子编程我要学编程
* Created by Sergio on 2015-05-25.
*/
public class Demo1 {
public static void main(String[] args) {
checkMail();
}
public static void checkMail() {
String mail = "123wer32453@sina.com.cn";
String regex = "[a-zA-Z0-9_]{6,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";
System.out.println(mail.matches(regex));
}
}