正则表达式有前匹配和后匹配,前匹配用?<=表示;后匹配用?=表示package com.sks.mq.core; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by john on 17/9/21. */ public class Test { public static void main(String[] args) { //我们的目标是替换掉"provisional" String url = "http://sks-provisional.oss-cn-qingdao.aliyuncs.com/9136393e6csdfsdf73ef6cceec8d80284de9.jpg"; //(?<=http://sks-) 表示找到在http://sks-之后的内容 //.*(?=.oss-cn-qingdao.aliyuncs.com/[0-9a-zA-Z]*.[gif|png|jpg])表示在.oss-cn-qingdao.aliyuncs.com/任意数字(字母).jpg|png|gif之前的内容 String regex = "(?<=http://sks-).*(?=.oss-cn-qingdao.aliyuncs.com/[0-9a-zA-Z]*.[gif|png|jpg])"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(url); while(matcher.find()) { System.out.println(matcher.group()); System.out.println(matcher.replaceAll("xxx")); } } }
JAVA如何前后匹配和替换
最新推荐文章于 2024-08-05 07:30:00 发布