JAVA中使用正则表达式的若干方法

  正则的具体写法不是重点,一般常用的还是比较简单的
  主要想说的是在JAVA里使用正则的几种情况
  先来定义两个变量:
  1、被查找的字符串:str
  2、要查找的关键字(或正则表达式):keywordPattern
  情况一:判断str里是否含有keywordPattern
  import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegTest { public static void main(String[] args) { String str = "我是人。。我是好人。。我是好男人。。- - !!"; Pattern keywordPattern = Pattern.compile("好男人"); Matcher matcher = keywordPattern.matcher(str); System.out.println(str.find()); } } 输出:true
  情况二:判断str是否完全符合keywordPattern,可用于邮箱验证等情况
  public class RegTest { public static void main(String[] args) { String str = "abcd1234ABCD"; Pattern keywordPattern = Pattern.compile("^[a-zA-Z0-9]+$"); Matcher matcher = keywordPattern.matcher(str); System.out.println(matcher.matches()); //System.out.println(matcher.find()); 也可以实现同样的效果 } } 输出:true
  情况三:将str中符合keywordPattern的字符都替换掉
  import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegTest { public static void main(String[] args) { String str = "abcd1234ABCD"; Pattern keywordPattern = Pattern.compile("[0-9]"); Matcher matcher = keywordPattern.matcher(str); System.out.println(matcher.replaceAll("@")); } } 输出: abcd@@@@ABCD
  情况四:将str中符合keywordPattern的字符替换掉一部分,某些被替换的字符还需保留
  import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegTest { public static void main(String[] args) { String str = "12[3]456[7]890"; Pattern keywordPattern = Pattern.compile("\\[(\\d)\\]"); Matcher matcher = keywordPattern.matcher(str); System.out.println(matcher.replaceAll("")); } } 输出:12456890
  情况五:将str中符合keywordPattern的字符替换掉一部分,某些被替换的字符还需做为参数进行处理
  import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegTest { public static void main(String[] args) { String str = "a[b]cdef[g]hij[k]lmn"; Pattern keywordPattern = Pattern.compile("\\[([a-z])\\]"); Matcher matcher = keywordPattern.matcher(str); StringBuffer strB = new StringBuffer(); while(matcher.find()){ matcher.appendReplacement(strB, getChar(matcher.group(1))); } matcher.appendTail(strB); System.out.print(strB.toString()); } public static String getChar(String num){ return "[" + num.toUpperCase() + "]"; } } 输出:a[B]cdef[G]hij[K]lmn
  其中第四和第五两种方法,可以实现 公式解析 和 模板解析等复杂功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值