JAVA正则表达式

JAVA正则表达式教程链接:菜鸟教程

java的正则表达式主要有三个类:Pattern、Matcher、PatternSyntaxException

以下实例中使用了正则表达式 .*runoob.* 用于查找字符串中是否包了 runoob 子串:

import java.util.regex.*;

class RegexExample1{
   public static void main(String args[]){
      String content = "I am noob " +
        "from runoob.com.";

      String pattern = ".*runoob.*";

      boolean isMatch = Pattern.matches(pattern, content);
      System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
   }
}

这里会输出:字符串中是否包含了 ‘runoob’ 子字符串? true

如果是查找字符串则可以这样使用

          String line = "Thisorderwashttps://www.baidu.com!OK?,absgdjsgh2345";
          String pattern = "http\\w*:\\D*\\.com";

          // 创建 Pattern 对象
          Pattern r = Pattern.compile(pattern);

          // 现在创建 matcher 对象
          Matcher m = r.matcher(line);
          while (m.find()) {
              System.out.println("Found value: " + m.group());
                            }
        //这里会输出https://www.baidu.com

正则表达式的替换方法有两个replaceFirst 和 replaceAll 方法

        //replaceAll  使用
         String line = "Thisorderwashttps://www.baidu.com!OK?,absgdjsgh2345";
          String pattern = "http\\w*:\\D*\\.com";
          // 创建 Pattern 对象
          Pattern r = Pattern.compile(pattern);

          // 现在创建 matcher 对象
          Matcher m = r.matcher(line);
          String string = m.replaceAll("https://www.google.com");
          System.out.println(string);
          //这里会输出Thisorderwashttps://www.google.com!OK?,absgdjsgh2345

        //replaceFirst
        String line = "Thisorderwashttps://www.google.com!OK?,absgdjsgh2345https://www.baidu.com";
          String pattern = "http\\w*:\\D*\\.com";
          // 创建 Pattern 对象
          Pattern r = Pattern.compile(pattern);

          // 现在创建 matcher 对象
          Matcher m = r.matcher(line);
          String string = m.replaceFirst("https://www.google.com");
          System.out.println(string);
          //这里会输出https://www.google.com

具体各个参数的使用方法要查询API文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值