Java开发(1) - 正则表达式

 带附件: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 = "<table> <tr><td>123ksdjfsld</td><td>34243kdljsfkldsf</td>kdlfjsdf</tr></table";
  48. Matcher m = Pattern.compile("<td>((\\d+)(\\w+)</td>").matcher(html);
  49. while(m.find()){
  50. int cnt = m.groupCount();
  51. System.out.println(cnt);
  52. for(int i=0;i<=cnt;i++){
  53. System.out.println("group" + i + ":" + m.group(i));
  54. }
  55. }
  56. }
  57.  
  58. @Test
  59. public void testGreedy2(){
  60. String html = "klsdjfl8394387592347ksjd";
  61. Matcher m = Pattern.compile("\\d+?").matcher(html); while(m.find()){
  62. System.out.println(m.group());
  63. }
  64. }
  65. }  

你可能感兴趣的:(java,开发,表达式)