"a b c".split("\\s"); // { "a", "b", "c" } "a b c".split("\\s"); // { "a", "b", "", "c" } "a, b ;; c".split("[\\,\\;\\s]+"); // { "a", "b", "c" }
搜索
1 2 3 4 5 6 7 8 9 10 11 12 13
import java.util.regex.*;
public class Main { public static void main(String[] args) { String s = "the quick brown fox jumps over the lazy dog."; Pattern p = Pattern.compile("\\wo\\w"); Matcher m = p.matcher(s); while (m.find()) { String sub = s.substring(m.start(), m.end()); System.out.println(sub); } } }
这个代码就是找中间有前面一个字符后面一个。中间有个o的字符
return
1 2 3
row fox dog
替换
1 2 3 4 5 6 7 8
// regex public class Main { public static void main(String[] args) { String s = "The quick\t\t brown fox jumps over the lazy dog."; String r = s.replaceAll("\\s+", " "); System.out.println(r); // "The quick brown fox jumps over the lazy dog." } }
return
1
The quick brown fox jumps over the lazy dog.
反向引用
1 2 3 4 5 6 7 8
// regex public class Main { public static void main(String[] args) { String s = "the quick brown fox jumps over the lazy dog."; String r = s.replaceAll("\\s([a-z]{4})\\s", " <b>$1</b> "); System.out.println(r); } }
return
1
the quick brown fox jumps <b>over</b> the <b>lazy</b> dog.