正则表达式在Java中应用的三种典型场合:验证,查找和替换

正则式在编程中常用,总结在此以备考:

复制代码
package regularexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegUsages {
// 验证例子
private static boolean verify(String code) { final String patternStr = "\\d+"; return Pattern.matches(patternStr, code); } // 查找例子 private static void search() { Pattern pattern = Pattern.compile("m(o+)n", Pattern.CASE_INSENSITIVE); Matcher matcher=pattern.matcher("Sun Earth moon mooon Mon mooooon Mooon Mars"); while(matcher.find()) { System.out.println(String.format("%s (%d~%d)", matcher.group(0),matcher.start(),matcher.end())); } } // 更替例子1 private static void replace1() { String str = "10元 1000人民币 10000元 100000RMB"; str = str.replaceAll("(\\d+)(元|人民币|RMB)", "$1圆"); System.out.println(str); } // 更替例子2 private static void replace2() { Pattern p = Pattern.compile("m(o+)n", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("Sun Earth moon mooon Mon mooooon Mooon Mars"); StringBuffer sb = new StringBuffer(); boolean result = m.find(); while (result) { m.appendReplacement(sb, "Moon"); result = m.find(); } m.appendTail(sb); System.out.println("Result=" + sb.toString()); } public static void main(String[] args) { System.out.println(String.format("601857 %s a stock code.",verify("601857")?"is":"isn't")); search(); replace1(); replace2(); } }
复制代码

输出:

601857 is a stock code.
moon (10~14)
mooon (15~20)
Mon (21~24)
mooooon (25~32)
Mooon (33~38)
10圆 1000圆 10000圆 100000圆
Result=Sun Earth Moon Moon Moon Moon Moon Mars

--2020-03-06--

posted @   逆火狂飙  阅读(195)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2019-03-06 【Canvas与电脑桌面壁纸】L形交错十字桌面(1920*1080)
2019-03-06 【Canvas技法】使用贝塞尔曲线模拟勾画渐开线齿轮轮廓
2019-03-06 【Canvas与艺术】大小渐开线齿轮传动
2019-03-06 【Canvas与艺术】旋转弯曲色带效果(类似曲叶电风扇)
2014-03-06 【Canvas与艺术】绘制蓝底三箭头白环循环标志
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示