字符串:正则表达式的使用
发布时间:2020-12-14 06:36:41 所属栏目:百科 来源:网络整理
导读:?? /* * 2018年3月30日15:53:17 * 代码目的: * 演示正则表达式java.util.regex中两个类的使用。 * 1, 导入java.util.regex * 2, 使用static Pattern.compile()方法来编译你的正则表达式, 它会根据你的String类型的正则表达式生成一个Pattern对象。 * 3,
??
/* //: strings/TestRegularExpression.java // Allows you to easily try out regular expressions. // {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" } import java.util.regex.*; import static net.mindview.util.Print.*; public class TestRegularExpression { public static void main(String[] args) { if(args.length < 2) { print("Usage:njava TestRegularExpression " + "characterSequence regularExpression+"); System.exit(0); } print("Input: "" + args[0] + """); for(String arg : args) { print("Regular expression: "" + arg + """); Pattern p = Pattern.compile(arg); Matcher m = p.matcher(args[0]); /* * Regular expression: "abc+" Match "abc" at positions 0-2 Match "abc" at positions 3-5 Match "abc" at positions 6-8 Match "abc" at positions 12-14 通过该输出,可以看到在字符串匹配一个模式时,会从头开始进行, 在第一次匹配时,匹配的位置是0--3,而匹配的内容由group()显示 起始和结束位置由start和end方法显示。 再次进入循环时,匹配从end方法所指向的位置开始进行。 * */ while(m.find()) { print("Match "" + m.group() + "" at positions " + m.start() + "-" + (m.end() - 1)); } } } } /* Output: Input: "abcabcabcdefabc" Regular expression: "abcabcabcdefabc" Match "abcabcabcdefabc" at positions 0-14 Regular expression: "abc+" Match "abc" at positions 0-2 Match "abc" at positions 3-5 Match "abc" at positions 6-8 Match "abc" at positions 12-14 Regular expression: "(abc)+" Match "abcabcabc" at positions 0-8 Match "abc" at positions 12-14 Regular expression: "(abc){2,}" Match "abcabcabc" at positions 0-8 *///:~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |