java中正则表达式的使用

一、判断字符串中是否含有某段字符串

Pattern.matches(String regex, String input)

示例

import java.util.regex.Pattern;

public class test {
     public static void main(String[] args) {
         String url = "www.baidu.com";
         String regex = "(.*)baidu(.*)";
         System.out.println(Pattern.matches(regex, url));
         //结果为true
     }
}

二、替换字符串的部分

replaceAll(String regex, String replacement)

示例

public class test {
     public static void main(String[] args) {
         
         String url = "www.baidu.com";

         String regex = "(\\w+)";
         String result2 = url.replaceAll(regex, "123");
         //结果为123.123.123
//如果想保留部分内容,那就用()表示那部分,替换部分用$表示 //如果有多个部分需要保留,那用多个$表示,并跟序号,表示第几个 //示例 String regex2 = "www\\.(.*)\\.(.*)"; String result = url.replaceAll(regex2, "$1,$2"); //结果为baidu,com } }

三、找出字符串的所有符合条件的字符串

示例

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

public class test {
     public static void main(String[] args) {
         //找出百度网址中全部由小写英文构成的字符串
        String url = "www.baidu.com";
        Pattern p = Pattern.compile("([a-z]+)");
        Matcher m = p.matcher(url);
        while (m.find()) {
            System.out.println(m.group());
            }
        /**
         * 结果
         * www
         * baidu
         * com
         * 
         */
     }
}

 

转载于:https://www.cnblogs.com/wei-jing/p/10463395.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值