Java中的正则表达式Regex

正则表达式(regulation expression)简称regex。是一个文本处理工具,用于匹配查找替换某种符合格式的字符串。

有两个最重要的类是pattern和matcher。

Pattern是正则表达式的编译表现形式。Matcher是用来执行匹配操作的引擎,具体操作如下:

public class Regex {
    public static void main(String[] args) {
        //1 定义正则表达式
        String regex="\\d+";//匹配一个或者多个数字
        //2 编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        //3 创建匹配器
        Matcher matcher = pattern.matcher("There are 123 numbers in this 45 string 789.");
        //4 查找匹配的子字符串
        while (matcher.find()){
            System.out.println(matcher.group());
        }
    }
}

Pattern的方法

  • Pattern compile(String regex): 编译给定的正则表达式。
  • Matcher matcher(CharSequence input): 创建一个匹配器对象。

Matcher的方法

  • boolean matches(): 尝试将整个输入序列与模式匹配。
  • boolean find(): 尝试查找输入序列中与该模式匹配的下一个子序列。
  • String group(): 返回前一次匹配操作所匹配的输入子序列。
  • int start(): 返回前一次匹配操作的初始索引。
  • int end(): 返回前一次匹配操作的最后一个字符的索引+1。

常用的正则表达式的语法

  • .: 匹配任何单个字符
  • \d: 匹配一个数字
  • \w: 匹配一个字母、数字或下划线
  • \s: 匹配任何空白字符
  • *: 匹配前面的子表达式零次或多次
  • +: 匹配前面的子表达式一次或多次
  • ?: 匹配前面的子表达式零次或一次
  • {n}: 匹配前面的子表达式恰好n次
  • {n,}: 匹配前面的子表达式至少n次
  • {n,m}: 匹配前面的子表达式至少n次,至多m次
  • ^: 匹配输入字符串的开始
  • $: 匹配输入字符串的结束
  • []: 匹配方括号内的任意一个字符
  • [^]: 匹配不在方括号内的任意字符
  • |: 逻辑或操作符

示例扩展:

匹配邮箱:

String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}";

匹配IP地址:

String regex = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

匹配日期:

String regex = "\\d{4}-\\d{2}-\\d{2}";

替换功能:

public class RegexReplaceExample {
    public static void main(String[] args) {
        String input = "The rain in Spain stays mainly in the plain.";
        String regex = "ain";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        // 替换所有匹配的子字符串
        String result = matcher.replaceAll("123");

        System.out.println(result); // 输出: The r123 in Sp123 stays m123ly in the pl123.
    }
}

注意事项:正则表达式的反斜杠需要双写”\\”因为在Java中\是转移字符

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值