正则表达式的贪婪,勉强,独占模式


public static void main(String[] args) {
String s = "xxyyxxxyxxyxx";
Pattern greedy = Pattern.compile("xx(.*)xx");
Pattern reluctant = Pattern.compile("xx(.*?)xx");
Pattern possessive = Pattern.compile("xx(.*+)xx");
Matcher m1 = greedy.matcher(s);
Matcher m2 = reluctant.matcher(s);
Matcher m3 = possessive.matcher(s);
while(m1.find()) {
System.out.println("greedy..." + m1.group(1));
}
while(m2.find()) {
System.out.println("reluctant..." + m2.group(1));
}
while(m3.find()) {
System.out.println("possessive..." + m3.group(1));
}
}


输出结果
greedy...yyxxxyxxy
reluctant...yy
reluctant...y

greedy (.*)吃掉整字符串,然后从最后一个字符开始回退,所以找到最后一个xx
reluctant (.*?)从左侧开始匹配最少的字符,每当找到一个xx结尾就匹配一次
possessive (.*+)因为吃掉整个字符串后面没有xx,而且不会进行回退,所以没有匹配到任何结果

一个用于替换字符串模式的例子:

public class StringAnalysis {
/**
* 将字符串中特定模式的字符转换成map中对应的值
*
* @param s
* 需要转换的字符串
* @param map
* 转换所需的键值对集合
* @return 转换后的字符串
*/
public static String convert(String s, Map<String, String> map) {
Matcher m = Pattern.compile("<#=(.*?)#>").matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String value = map.get(m.group(1));
m.appendReplacement(sb, value != null ? value : "null");
}
m.appendTail(sb);
return sb.toString();
}

public static void main(String[] args) {
String str = "姓名:<#=name#>\n性别:<#=sex#>\n住址:<#=address#>\n联系方式:<#=linkinf#>";
Map<String, String> map = new HashMap<String, String>();
map.put("xxx", "哈哈");
map.put("name", "Steven");
map.put("address", "XX市XX区XXX二路X-X号X室");
map.put("linkinf", "13577777777");

System.out.println(convert(str, map));
}
}

输出结果:
姓名:Steven
性别:null
住址:XX市XX区XXX二路X-X号X室
联系方式:13577777777
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值