您的位置:首页 > 编程语言 > Java开发

Java中正则表达式的实现_代码

2008-10-17 17:56 555 查看
import java.util.regex.Matcher;

import java.util.regex.Pattern;

/**

* @author jiakw

* 正则表达式的使用

*/

public class TestRegex {

/**

* 字符串匹配

* @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[i]);

}

}

/**

* @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");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: