正则

来源:互联网 发布:淘宝宝贝上传教程 编辑:程序博客网 时间:2024/05/04 13:28

正则对象

 

Pattern 正则表达式的封装类,其实也就是将一个字符串包装一下罢了。有点多余这个类。

//静态方法将参数指定的字符串封装成正则对象。
public static Pattern compile(String regex) 


//将一个正则对象与需要操作的字符串绑定,并返回一个匹配器,绑定的字符串可以是以下任意一种。
//CharBuffer, Segment, String, StringBuffer, StringBuilder 使用这种方式可以对Buffer与Builder使用正则。
public Matcher matcher(CharSequence input) 


完成以上两步后,使用得到的Matcher匹配器对象即可对绑定的字符串经行多种正则匹配操作。如:

//匹配
public boolean matches()

//替换
public String replaceAll(String replacement)

//获取,即反向切割
public String group()


  需要注意的是,当使用group时,应该先使用public boolean find()方法对绑定的字符串内容经行查找,使Matches匹配器内部维护的索引指针指向符合正则规则的正确位置。每一次对匹配器使用匹配替换获取等操作时,都会影响到索引指针,如匹配后索引指针会移动到。

 

//可以重围当前匹配器的索引指针,参数可以用来指定一个新的绑定字符串
public Matcher reset(CharSequence input)

  当使用find方法查找到正确的匹配结果后可以使用start与end方法获取当前匹配正确结果后的子串在父串中索引前后位置。

 

 

String类提供了常用的正则匹配方法。

//匹配
public boolean matches(String regex)
//替换
public String replaceAll(String regex, String replacement)
//切割
public String[] split(String regex)

 

 

正则规则

[]中括号可以用来指定字符串中的一个索引位的匹配结果,[a-z]所有小写,[0]单个字符,常用符号有\\d数字,\\w标准字符:[a-zA-Z_0-9]。

{}大括号用来指定前一个索引位的次数。{1,5}一到五次,{5,}最少五次,{9}九次,常用符号有+一次多次,*零次多次。

()小括号内的内容被编制成一个组,可以在同一个正则中使用\\0 - N的形式重用该组内容0为整个原字符串,在正则作用于替换时可以使用$0-N来

重用正则规则中被编制的组。


当表达式为单个符号或字符时括号可以省略不写。

 

 

代码演示

 

static void getAllTele() {String tele = "kajsdf;wlke10884324909fjoisdf15983230098asdfasd13909876655asdfe13823455sf";Pattern pat = Pattern.compile("1[358]\\d{9}");Matcher mat = pat.matcher(tele);while(mat.find()) {System.out.println(mat.group());}}static void checkEmail() {String email = "slatop@qq.com";//\\w&&[^_]&&[^\\d]其实相当于a-zA-ZPattern pat = Pattern.compile("[a-zA-Z][\\w]{5,18}@[\\w&&[^_]]{2,8}(\\.[\\w&&[^_]&&[^\\d]]+)+");Matcher mat = pat.matcher(email);System.out.println(mat.matches());}static void deleteDirty() {String text = "你妈如果这样可以不你爸这个不知道是不是滚蛋有这样一天操了为为为为什么不操操!";Pattern pat = Pattern.compile("[妈爸[滚蛋]操]");Matcher mat = pat.matcher(text);text = mat.replaceAll("*");System.out.println(text);}


 

原创粉丝点击