字符串:正则表达式的使用

xiaoxiao2021-02-28  18



/* * 2018年3月30日15:53:17 * 代码目的: *     演示正则表达式java.util.regex中两个类的使用。 *     1, 导入java.util.regex *     2, 使用static Pattern.compile()方法来编译你的正则表达式,    它会根据你的String类型的正则表达式生成一个Pattern对象。 *     3, 把你想要检索的字符串传入Pattern对象的matcher()方法 *     4, matcher()方法会生成一个Matcher对象,有很多功能可用, *           它的replaceAll()方法能将所有匹配的部分都替换成你传入的参数。 *            *         该程序需要使用命令行参数 * */

//: 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 *///:~
转载请注明原文地址: https://www.6miu.com/read-1899988.html

最新回复(0)