首页 | 源码下载 | 网站模板 | 网页特效 | 广告代码 | 网页素材 | 字体下载 | 书库 | 站长工具
会员投稿 投稿指南 RSS订阅
当前位置:主页>网络编程>java教程>资讯:Java 字符串正则表达式使用

Java 字符串正则表达式使用

www.jz123.cn  2010-10-08   来源:   中国建站    责任编辑(袁袁)    我要投递新闻

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

/**
* @author odd
* 正则表达式的使用
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {

matchingText("^hi.*Ly.*","hi is Ly ");
matchingText("0\\d{2}-\\d{3}","011-112");
matchingText("^\\d{3,4}[-]\\d{8}$","0111-12345678");
/*
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");
*/
}

/**
* 字符串匹配
* @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);
*/
System.out.println( Pattern.compile(expression).matcher(text).matches());
}

/**
* 字符串替换
* @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[i]);
}
}

}


上一篇:Java制作水印图片源码 下一篇:使用实时Java降低Java应用程序的易变性(1)

评论总数:0 [ 查看全部 ] 网友评论


关于我们隐私版权广告服务友情链接联系我们网站地图