Java正则表达式学习教程(2)

System.out.println(Pattern.matches("(\\w\\d)\\1", "a2a2")); //true System.out.println(Pattern.matches("(\\w\\d)\\1", "a2b2")); //false System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B2AB")); //true System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B3AB")); //false

在第一个例子里,运行的时候第一个capturing group是(\w\d),在和输入字符串“a2a2″匹配的时候获取“a2″并保存到内存里。因此\1是”a2”的引用,并且返回true。基于相同的原因,第二行代码打印false。

试着自己理解第三行和第四行代码。:)

现在我们来看看Pattern和Matcher类中一些重要的方法。

我们可以创建一个带有标志的Pattern对象。例如Pattern.CASE_INSENSITIVE可以进行大小写不敏感的匹配。Pattern类同样提供了和String类相似的split(String) 方法

Pattern类toString()方法返回被编译成这个pattern的正则表达式字符串。

Matcher类有start()和end()索引方法,他们可以显示从输入字符串中匹配到的准确位置。

Matcher类同样提供了字符串操作方法replaceAll(String replacement)和replaceFirst(String replacement)。

现在我们在一个简单的java类中看看这些函数是怎么用的。

package com.journaldev.util; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples { public static void main(String[] args) { // using pattern with flags Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher("ABcabdAb"); // using Matcher find(), group(), start() and end() methods while (matcher.find()) { System.out.println("Found the text \"" + matcher.group() + "\" starting at " + matcher.start() + " index and ending at index " + matcher.end()); } // using Pattern split() method pattern = Pattern.compile("\\W"); String[] words = pattern.split("one@two#three:four$five"); for (String s : words) { System.out.println("Split using Pattern.split(): " + s); } // using Matcher.replaceFirst() and replaceAll() methods pattern = Pattern.compile("1*2"); matcher = pattern.matcher("11234512678"); System.out.println("Using replaceAll: " + matcher.replaceAll("_")); System.out.println("Using replaceFirst: " + matcher.replaceFirst("_")); } }

上述程序的输出:

Found the text "AB" starting at 0 index and ending at index 2 Found the text "ab" starting at 3 index and ending at index 5 Found the text "Ab" starting at 6 index and ending at index 8 Split using Pattern.split(): one Split using Pattern.split(): two Split using Pattern.split(): three Split using Pattern.split(): four Split using Pattern.split(): five Using replaceAll: _345_678 Using replaceFirst: _34512678

这是不是一个很全面的Java正则表达式学习教程,希望对大家的学习有所帮助。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjpzwp.html