正则表达式:Pattern 与Matcher
????java.util.regex包是一個用于匹配字符序列與正則表達式指定的類庫包。這個包中包含有三個類:Pattern、Matcher和PatternSyntaxException.
????Pattern:正則表達式經編譯后的表現模式
????Matcher:一個Matcher對象是一個狀態機器,依據Pattern對象作為匹配模式對字符串展開匹配檢查。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
使用流程:
????首先使用Pattern的一個靜態方法Complie來創建Pattern對象。
????????Pattern n=Pattern.Complie(regax);
????然后,調用Pattern的方法matcher
????????Matcher m=p.matcher(Candidate);
????得到Matcher對象,Matcher對象保存了許多匹配信息,通過find()方法查找匹配的部分,若有,返回TRUE,m.group()可得到匹配的各組值,否則,返回FALSE。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Pattern類的方法:
????1、Static Pattern compile(String regex);
????????將給定的正則表達式編譯并賦予給Parrern類;
? ?????Static Pattern compile(String regex,int flags);
????2、int flags();
????????返回當前Pattern的匹配flags參數;
????3、Matcher matcher(CharSequeue input);
????????生成一個給定命名的Matcher對象;
????4、Static boolean matchers(String regex,CharSequeue intput);
????????編譯給定的正則表達式并且對輸入的字符串以該正則表達式為模式展開匹配,該方法適合于該正則表達式只會使用一次的情況,也就是只進行一次匹配工作,因為這種情況下,不需要生成一個Matcher實例。
????5、String Pattern();?
????????返回該Pattern對象所編譯的表達式
????6、String[] Split(CharSequeue input);
????????將目標字符串按照Pattern里所包含的正則表達式為模式進行分割。
????? ? String[] Split(CharSequeue input,int limit);//limit為指定分割的段數
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Matcher類的方法:
????
????1、Matcher appendReplacement(StringBuffer sb,String replacement);
????????將當前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里。
????2、StringBuffer appendTail(StringBuffer sb);
????????將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。
????3、int end();
????????返回當前匹配的子串的最后一個字符串在原目標字符串的索引位置。????????
????? ?int end(int group);
????????返回與匹配模式里指定的但相匹配的子串最后一個字符的位置。
????4、boolean find();
????????嘗試在目標字符串里查找下一個匹配子串
????? ?boolean find(int start);
????????重設Matcher對象,并且嘗試在目標字符串里從指定的位置開始查找下一個匹配的子串。
????5、String group();
????????返回當前查找而獲得的與組匹配的所有子串內容
????? ?String group(int group);
????????返回當前查找而獲得的與指定的組匹配的子串內容
????? ?int groupCount();
????????返回當前查找所獲得匹配組的數量。
????6、boolean lookingAt();
????????檢測目標字符串是否以匹配的子串起始
????7、boolean matches();
????????嘗試對整個目標字符串展開匹配檢測,也就是對整個目標字符串完全匹配時才返回值。
????8、Pttern pattern();
????????返回該Matcher對象的現有匹配模式,也就是對應的Pattern對象。
????9、String replaceAll(String replacement);
????????將目標字符串里的所有與既有模式相匹配 的子串替換為指定的字符串
????10、String replaceFirst(String repalcement);
????????只替換第一個。。。。。。。。。。。。。
????11、Matcher reset()//重設該Matcher對象
????????Matcher reset()//重設該Matcher對象,并且制定一個新的目標字符串
????12、int start();
????????返回當前查找所獲子串的開始字符在原目標字符串中的位置。
????13、int start(int group);
????????返回當前查找所獲得的和指定組匹配的子串的第一個字符在原目標字符串中的位置。
轉載于:https://blog.51cto.com/jx610/1572091
總結
以上是生活随笔為你收集整理的正则表达式:Pattern 与Matcher的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Common tasks for MyS
- 下一篇: Linux下通过设置PS1变量改变bas