JAVA中正則表達式常用的四個方法


  JAVA中正則表達式處理字符串的四個常用方法:匹配、分割、替換、截取。其跟字符串的常用函數相似,但是使用正則表達式會更簡單、更加簡潔。下面是具體的例子:

 

 1 public class TestRegex {
 2 
 3     public static void main(String[] args) {
 4         String str = "";
 5         String regex = "";
 6 
 7         // 匹配
 8         regex = "[1-9][a-z]";
 9         getMatches(str, regex);
10 
11         // 分割
12         str = "1a<a>:abc123:</a>";
13         regex = ":";
14         getSpilt(str, regex);
15 
16         // 替換
17         str = "1223334444aaabbc";
18         String oldChar = "(.)\\1+";
19         regex = "$1";
20         getReplace(str, oldChar, regex);
21         
22         // 截取
23         str = "<title>test string</title><a>url</a><content>abc123</content>";
24         regex = "<a>(.*)</a>";
25         getSubstring(str, regex);
26 
27     }
28 
29     public static void getMatches(String str, String regex) {
30         System.out.println(str.matches(regex));
31     }
32 
33     public static void getSpilt(String str, String regex) {
34         String[] array = str.split(regex);
35         for (String t : array) {
36             System.out.println(t);
37         }
38     }
39 
40     public static void getReplace(String str, String oldChar, String regex) {
41         System.out.println(str.replaceAll(oldChar, regex));
42     }
43 
44     public static void getSubstring(String str, String regex) {
45         Pattern p = Pattern.compile(regex);
46         Matcher m = p.matcher(str);
47         if (m.find()) {
48             System.out.println(m.group(1));
49         }
50     }
51 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM