赞
踩
String提供了一个匹配正则表达式的方法
public boolean matches(String regex(正则表达式)) 判断字符串是否匹配正则表达式,匹配返回true,否则false
正则表达式的书写规则:
需求:检验用户输入的电话、邮箱、时间是否合法
代码:
- import java.util.Scanner;
-
- public class CheckPhoneEmailTime {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- while (true) {
- System.out.print("请输入你要校验的手机号码or邮箱or时间(输入0退出):");
- String str = sc.nextLine();
- if(str.equals("0")) break;
- if(str.matches("(1[3-9]\\d{9})|" + //手机号码
- "0\\d{2,3}-?[1-9]\\d{6,7}|" + //座机号码
- "\\w{2,}@\\w{2,20}\\.\\w{2,10}|" + //邮箱号码
- "([0-1]\\d)|(2[0-4])((:)|(-)|(\\.))[0-5]\\d((:)|(-)|(\\.))[0-5]\\d")) //时间格式
- System.out.println("格式正确");
- else
- System.out.println("格式错误");
- }
- }
- }

运行结果:
- import java.util.Arrays;
-
- public class Regex_test {
- public static void main(String[] args) {
- // public String replaceAll(String regex , String newStr); 按照正则表达式匹配的内容进行替换
-
- //1.请把古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴 中间的非中文字符替换成"-"
- String s1 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
- System.out.println(s1.replaceAll("\\w+", "-")); //+表示一或多
-
- //2.请把我我我喜欢编编编编编编编编编编编编程程程! 替换成我喜欢编程!
- // (.) 匹配任意字符, ()表示一组
- // \\1 为这个组声明一个组号:1 标记它
- // {2,} 表示这个字至少出现俩次
- // $1取出标记的那个组的内容
- String s2 = "我我我喜欢编编编编编编编编编编编编程程程!";
- System.out.println(s2.replaceAll("(.)\\1{2,}", "$1"));
-
- //public string[]split(string regex):按照正则表达式匹配的内容进行分割字符串,反回一个字符串数组。
- //3.请把 古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴 中的人名获取出来。
- String s3 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
- System.out.println(Arrays.toString(s3.split("\\w+")));
- }
- }

运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。