String和Pattern中的正則表達式使用起來有什么區別
1 回答

BIG陽
TA貢獻1859條經驗 獲得超6個贊
正則表達式本身沒有區別,String中也是調用的Pattern
比如String的split、replace、replaceAll等方法,進入源碼就可以看到里面其實就是調用的Pattern
12345 | // String replace 源碼 public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this ).replaceAll(Matcher.quoteReplacement(replacement.toString())); } |
1234 | // String replaceAll 源碼 public String replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher( this ).replaceAll(replacement); } |
如果一定要說區別,那就是如果頻繁使用同一個正則表達式,使用Pattern相對更好一些。這里的好指的定義一個Pattern,重復使用。看Pattern的源碼可以看到Pattern.compile(regex)是要new一個對象的,所以String每次是創建了一個新的Pattern對象。大量頻繁使用同一個正則,明顯是自己構建重用效率更好。
1234 | // Pattern compile 源碼 public static Pattern compile(String regex) { return new Pattern(regex, 0 ); } |
- 1 回答
- 0 關注
- 727 瀏覽
添加回答
舉報
0/150
提交
取消