總結幾個正則表達式平時使用過程當中表的疑惑點,總結結果以下:正則表達式
\.(jpg|png|bmp|gif) 上面這個正則表達式爲何有兩個反斜槓呢?反斜槓點.就能表示點.了,爲何還要在.前面多加一個\?bash
答案:這要分兩步看 首先字符串中的\被編譯器解釋爲
而後做爲正則表達式,.又被正則表達式引擎解釋爲.測試
若是在字符串裏只寫.的話,第一步就被直接解釋爲.,以後做爲正則表達式被解釋時就變成匹配任意字符了spa
網上相似的博客不少,可是看他們的說法實驗結果各異,因而我本身測了一把,得出以下結論。code
在Matcher類中有matches、lookingAt和find都是匹配目標的方法,但容易混淆,整理它們的區別以下:對象
測試代碼:字符串
private void regexTest(){
Pattern pattern = Pattern.compile("\\d{3,5}");
String charSequence = "123-34345-234-00";
Matcher matcher = pattern.matcher(charSequence);
//雖然匹配失敗,但因爲charSequence裏面的"123"和pattern是匹配的,因此下次的匹配從位置4開始
Log.e("regex",""+matcher.matches());
//測試匹配位置
matcher.find();
Log.e("regex",""+matcher.start());
//使用reset方法重置匹配位置
matcher.reset();
//第一次find匹配以及匹配的目標和匹配的起始位置
Log.e("regex",""+matcher.find());
Log.e("regex",""+matcher.group()+" - "+matcher.start());
//第二次find匹配以及匹配的目標和匹配的起始位置
Log.e("regex",""+matcher.find());
Log.e("regex",""+matcher.group()+" - "+matcher.start());
//第一次lookingAt匹配以及匹配的目標和匹配的起始位置
Log.e("regex",""+matcher.lookingAt());
Log.e("regex",""+matcher.group()+" - "+matcher.start());
//第二次lookingAt匹配以及匹配的目標和匹配的起始位置
Log.e("regex",""+matcher.lookingAt());
Log.e("regex",""+matcher.group()+" - "+matcher.start());
//使用reset方法重置匹配位置
matcher.reset();
//遍歷全部匹配的子串
while(matcher.find()){
Log.e("regex",""+matcher.group()+" - "+matcher.start());
}
}
複製代碼
測試結果:編譯器
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: false
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 0
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: true
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 123 - 0
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: true
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 34345 - 4
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: true
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 123 - 0
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: true
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 123 - 0
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 123 - 0
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 34345 - 4
2018-12-28 14:55:40.675 15023-15023/com.kdgw.weifeng.runnumber E/regex: 234 - 10
複製代碼