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

相关文章

jquery.validate使用攻略(表单校验) 目录 jquery.validate...
/\s+/g和/\s/g的区别 正则表达式/\s+/g...
自整理几个jquery.Validate验证正则: 1. 只能输入数字和字母...
this.optional(element)的用法 this.optional(element)是jqu...
jQuery.validate 表单动态验证 实际上jQuery.validate提供了...
自定义验证之这能输入数字(包括小数 负数 ) &lt;script ...