`
hypercube1024
  • 浏览: 83835 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多
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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics