带附件:JAVA正则表达式详解(书籍)

Java代码
  1. package com.tests;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. import org.junit.Test;
  5.  
  6. public class TestPatternMatcher {
  7.  
  8. @Test
  9. public void TestReplaceAll(){
  10. String s="Hello World ...";
  11.  
  12. String s2=s.replaceAll("\\.", "");
  13. System.out.println(s2);
  14.  
  15. String s3=s.replaceAll("\\S", "");
  16. System.out.println(s3);
  17.  
  18. String sLineSep = System.getProperty("line.separator");
  19. String s4 = "abcdefg" + sLineSep + "中国";
  20. System.out.println(s4);
  21. System.out.println(s4.replace(sLineSep, "换行"));
  22.  
  23. String s5 = "1985-01-17,在这个日期23423-2384-出生";
  24. Pattern pattern = Pattern.compile("\\d+");
  25. Matcher m = pattern.matcher(s5);
  26. while(m.find()){
  27. System.out.println(m.group()+"["+m.start()+"]-["+m.end()+"]");
  28. }
  29.  
  30.  
  31. String s6="just do do do do it~!123abc@@1234efg ";
  32. // Pattern pdo=Pattern.compile("do\\s(do\\s)+");
  33. Pattern pdo=Pattern.compile("\\d+(\\w+)");
  34. Matcher mdo = pdo.matcher(s6);
  35. while (mdo.find()) {
  36. for (int i = 0; i < mdo.groupCount(); i++) {
  37. // System.out.println(mdo.group() + "[" + mdo.start() + "]-["
  38. // + mdo.end() + "]");
  39. System.out.println(i+":"+mdo.group(i));
  40. }
  41. }
  42.  
  43. }
  44.  
  45. @Test
  46. public void testGreedy(){
  47. String html = "kdlfjsdf;
  48. Matcher m = Pattern.compile("
  49. ").matcher(html);
  50. while(m.find()){
  51. int cnt = m.groupCount();
  52. System.out.println(cnt);
  53. for(int i=0;i<=cnt;i++){
  54. System.out.println("group" + i + ":" + m.group(i));
  55. }
  56. }
  57. }
  58.  
  59. @Test
  60. public void testGreedy2(){
  61. String html = "klsdjfl8394387592347ksjd";
  62. Matcher m = Pattern.compile("\\d+?").matcher(html); while(m.find()){
  63. System.out.println(m.group());
  64. }
  65. }
  66. }  
  67. 你可能感兴趣的:(Java,开发,表达式)

    123ksdjfsld34243kdljsfkldsf
    ((\\d+)(\\w+)