前言
regex 应用广泛 用来对数据的格式进行检验 ,进行输入数据的规范约束.
还在 字符串的分割 匹配 替换 查找中 使用
提示:以下是本篇文章正文内容,下面案例可供参考
一、正则基础
- 补充\b 表示字母数字与非字母数字字符的边界,非字母数字与字母数字的边界。
- ^开始 $结束
- { , }左边至少 右边最多
二、使用步骤
- Pattern 模板
- Matcher 匹配
1.匹配检验
代码如下(示例):
String regex1 = "[a-zA-Z0-9]";
String s1 = "a",s2 = "我",s3 = "7";
// 最麻烦
Pattern pattern = Pattern.compile(regex1);
Matcher matcher = pattern.matcher(s1);
System.out.println(matcher.matches());
//Pattern 中有个静态方法简化
System.out.println(Pattern.matches(regex1,s1));
//string 中也有这个简便方法
System.out.println(s1.matches(regex1));
2.分割
代码如下(示例):
//分割
String str1 = "public=static==void====main======String[]=args";
String[] strings = str1.split("[=]+");
该处使用的url网络请求的数据。
3.替换
//替换(删除)
String str = "1234yu";
String s = str.replaceAll("[0-9]","");
4.查找
查找没有简化 , 需要matcher 继续用 find 方法来遍历
//查找
String data = "public static void main String[] args)";
Pattern wordPattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher3 = wordPattern.matcher(data);
int count = 0;
while (matcher.find()){
count++;
System.out.println(matcher.group()+"\t"+matcher.start()+"\t"+matcher.end());
}
System.out.println(count);
总结
代码运行结果如下:
一下时一些关于正则的例题一起分享给大家