Java中正则表达式类的一些使用

JAVA正则表达式类的使用

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author ZhuYuanXi
* 正则表达式的使用
*/
public class Test {

/**
* 字符串匹配
* @param expression 正则表达式字符串
* @param text 要进行匹配的字符串
*/
private static void matchingText(String expression, String text) {
   Pattern p = Pattern.compile(expression); // 正则表达式
   Matcher m = p.matcher(text); // 操作的字符串
   boolean b = m.matches();
   System.out.println(b);
}

/**
* 字符串替换
* @param expression 正则表达式字符串
* @param text 要进行替换操作的字符串
* @param str 要替换的字符串
*/
private static void replaceText(String expression, String text, String str) {
   Pattern p = Pattern.compile(expression); // 正则表达式
   Matcher m = p.matcher(text); // 操作的字符串
   String s = m.replaceAll(str);
   System.out.println(s);
}

/**
* 字符串查找
* @param expression 正则表达式字符串
* @param text 要进行查找操作的字符串
* @param str 要查找的字符串
*/
private static void findText(String expression, String text, String str) {
   Pattern p = Pattern.compile(expression); // 正则表达式
   Matcher m = p.matcher(text); // 操作的字符串
   StringBuffer sb = new StringBuffer();
   int i = 0;
   while (m.find()) {
    m.appendReplacement(sb, str);
    i++;
   }
   m.appendTail(sb);
   System.out.println(sb.toString());
   System.out.println(i);
}

/**
* 字符串分割
* @param expression 正则表达式字符串
* @param text 要进行分割操作的字符串
*/
private static void splitText(String expression, String text) {
   Pattern p = Pattern.compile(expression); // 正则表达式
   String[] a = p.split(text);
   for (int i = 0; i < a.length; i++) {
    System.out.println(a
);
   }
}

/**
* @param args
*/
public static void main(String[] args) {
   matchingText("^card_([_0-9a-zA-Z]+[_0-9a-zA-Z-/]*[_0-9a-zA-Z]+)/?.shtml$", "card_1020000000.shtml");
   // 字符串匹配,这是不符合的
   matchingText("a*b", "baaaaab");
   // 字符串匹配,这是符合的
   matchingText("a*b", "aaaaab");
   // 字符串匹配,通用匹配
   matchingText("^([_0-9a-zA-Z]+[_0-9a-zA-Z-/]*[_0-9a-zA-Z]+)/?", "aaaaab");

   // 字符串替换
   replaceText("ab", "aaaaab", "d");
   replaceText("a*b", "aaaaab", "d");
   replaceText("a*b", "caaaaab", "d");

   // 字符串查找
   findText("cat", "one cat two cats in the yard", "dog");
   findText("(fds){2,}", "dsa da fdsfds aaafdsafds aaf", "dog");
  
   // 字符串分割
   splitText("a+", "caaaaaat");
   splitText("a+", "c aa aaaa t");
   splitText(" +", "c aa    aaaa t");
   splitText("//+", "dsafasdfdsafsda+dsagfasdfa+sdafds");
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值