JAVA学习-笔记09-正则

Java 正则表达式

Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。

Matcher 类:
Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。

PatternSyntaxException:
PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。


正则检测:
String content = "I am noob from runoob.com.";
String pattern = ".*runoob.*";
System.out.println(Pattern.matches(pattern, content));


正则匹配获取结果:
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";
Matcher m = Pattern.compile(pattern).matcher(line);   //要求整个序列都匹配
Matcher m = Pattern.compile(pattern).lookingAt(line);  //不需要整句都匹配
if(m.find()){//正则查找
    System.out.println("Found value: " + m.group(0) );  //获取正则结果
    System.out.println("Found value: " + m.group(1) );
    System.out.println("Found value: " + m.group(2) );
    System.out.println("Found value: " + m.group(3) ); 
}else{
    System.out.println("NO MATCH");
}


正则替换:
String REGEX = "dog";
String INPUT = "The dog says meow. All dogs say meow.";
String REPLACE = "cat";
Matcher m = Pattern.compile(REGEX).matcher(INPUT); 
System.out.println(m.replaceFirst(REPLACE));  //替换首次匹配
System.out.println(m.replaceAll(REPLACE));  //替换所有匹配


String REGEX = "a*b";
String INPUT = "aabfooaabfooabfoobkkk";
String REPLACE = "-";
Matcher m = Pattern.compile(REGEX).matcher(INPUT);
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,REPLACE);
}
System.out.println(sb.toString());  //-foo-foo-foo-
m.appendTail(sb); 
System.out.println(sb.toString());  //-foo-foo-foo-kkk

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值