(3)正则补充

1. 量词的小细节,贪婪与懒惰
2. find()/find(i)方法
3. (?m) 单行模式 :标记的作用及用法(了解,用到时扩展)
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TestRegex {
	
	public static void main(String[] args) {
		String str = "abcabcabc";
		System.out.println(str.replaceFirst("(abc)+", "---"));  //abc出现一次或多次
		System.out.println(str.replaceFirst("abc+", "---"));    //ab后面的C出现一次或多次
		
		System.out.println(str.replaceFirst("\\S+?", "---"));   //贪婪模式,尽力匹配
		System.out.println(str.replaceFirst("\\S+", "---"));    //懒惰模式, 最少匹配
		
		StringBuilder sb = new StringBuilder();
		Matcher m = Pattern.compile("\\w+").matcher("Evening is full of the linnet's wings");
		while(m.find()) {
			sb.append(m.group()).append(" ");
		}
		System.out.println(sb.toString());
		sb.setLength(0);
		int i = 0;
		while(m.find(i)) {  //设置find的起点
			sb.append(m.group()).append(" ");
			i++;
		}
		System.out.println(sb.toString());
		sb.setLength(0);
		
		String str2 = "i have a big ice\n" + 
		              "you not have ice\n";
		//(?m)启动单行模式,此时^$符号表示每行的开头结尾,而不是整个字符串的开头结尾
		Matcher m2 = Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(str2);
		while(m2.find()) {
			for(int j=0; j<=m2.groupCount(); j++) {
				sb.append("[").append(m2.group(j)).append("]");
			}
			System.out.println(sb.toString());
			sb.setLength(0);
		}
		
		//find matches lookingAt区别
	}
	
}
//output
---
---abcabc
---bcabcabc
---
Evening is full of the linnet s wings 
Evening vening ening ning ing ng g is is s full full ull ll l of of f the the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s 
[a big ice][a][big ice][big][ice]
[not have ice][not][have ice][have][ice]

4. appendReplacement() 、appendTail()

5.reset()

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

public class TestRegex2 {

	public static void main(String[] args) {
		Pattern p = Pattern.compile("cat");
		Matcher m = p.matcher("one cat two cats in cat the cat yard cat");
		StringBuffer sb = new StringBuffer();
		int i = 0;
		while (m.find()) {
			if (i % 2 == 0) {
				m.appendReplacement(sb, "dog");
			}
			i++;
		}
		m.appendTail(sb);
		System.out.println(sb.toString());
		sb.setLength(0);

		// reset()重新matcher字符串
		m.reset("one cat two cats in the yard");
		while (m.find()) {
			m.appendReplacement(sb, "dog");
		}
		m.appendTail(sb);
		System.out.println(sb.toString());
	}

}
//output
one dog two cats in dog the cat yard dog
one dog two dogs in the yard



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值