正则表达式的使用(2)

xiaoxiao2021-02-28  99

正则表达式简单代码实例

package cn.hncu;

import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; public class Zhengze { @Test public void demo1() { String str = "010-2328322"; String reg = "0\\d{2,3}-\\d{7,8}";// 在java中要用双斜杠,表示转义字符 boolean boo = str.matches(reg); System.out.println(boo);// t } /* * 正则表达式的高级用法 利用jav.util.regex包中pattern和matcher类 助理解:前者代表正则工具,后者代表匹配结果 * 判断是否匹配,也可搜索符合正则表达式的内容 */ @Test public void demo2() { String str = "1010-12345678  222"; Pattern p = Pattern.compile("0\\d{2,3}-\\d{7,8}");// compile 将给定的正则表达式编译到模式中。 Matcher m = p.matcher(str);// 利用正则表达式开始匹配 boolean boo = m.matches();// 判断"整个完整的输入串'是否匹配,要判断整个串(整体) System.out.println(boo);// f //boolean boo2 = m.find(0);// 指定从0个字符开始查找 boolean boo2 = m.find(); //find 尝试查找与该模式匹配的输入序列的下一个子序列。 // 这里是判断输入串中是否存在一部分符合reg的子串(部分) System.out.println(boo2);// true //查找并输出所有查找到的匹配子串 String res = m.group(0);//输出第i个匹配串 System.out.println(res);//010-12345678 }

}

正则表达式扩展

转载请注明原文地址: https://www.6miu.com/read-19764.html

最新回复(0)