JAVA中正则表达式常用的四个方法

  JAVA中正则表达式处理字符串的四个常用方法:匹配、分割、替换、截取。其跟字符串的常用函数相似,但是使用正则表达式会更简单、更加简洁。下面是具体的例子:

 

复制代码
 1 public class TestRegex {
 2 
 3     public static void main(String[] args) {
 4         String str = "";
 5         String regex = "";
 6 
 7         // 匹配
 8         regex = "[1-9][a-z]";
 9         getMatches(str, regex);
10 
11         // 分割
12         str = "1a<a>:abc123:</a>";
13         regex = ":";
14         getSpilt(str, regex);
15 
16         // 替换
17         str = "1223334444aaabbc";
18         String oldChar = "(.)\\1+";
19         regex = "$1";
20         getReplace(str, oldChar, regex);
21         
22         // 截取
23         str = "<title>test string</title><a>url</a><content>abc123</content>";
24         regex = "<a>(.*)</a>";
25         getSubstring(str, regex);
26 
27     }
28 
29     public static void getMatches(String str, String regex) {
30         System.out.println(str.matches(regex));
31     }
32 
33     public static void getSpilt(String str, String regex) {
34         String[] array = str.split(regex);
35         for (String t : array) {
36             System.out.println(t);
37         }
38     }
39 
40     public static void getReplace(String str, String oldChar, String regex) {
41         System.out.println(str.replaceAll(oldChar, regex));
42     }
43 
44     public static void getSubstring(String str, String regex) {
45         Pattern p = Pattern.compile(regex);
46         Matcher m = p.matcher(str);
47         if (m.find()) {
48             System.out.println(m.group(1));
49         }
50     }
51 }
复制代码

 

posted @   PC君  阅读(3847)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2016-06-07 freemarker常用值格式化方法
2016-06-07 错误:Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp;的解决

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示