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

java 正则

2015-06-19 13:19 639 查看
原文:http://www.journaldev.com/634/java-regular-expression-tutorial-with-examples

。。。。。省略若干文字(介绍了java正则的通配符、基本语法等)

Regular Expression Capturing Groups(正则捕获组)

Capturing groups are used to treat multiple characters as a single unit.  You can create a group using
(). The portion of input String that matches the capturing group is saved into memory and can be recalled using
Backreference.

捕获组可以将多个字符作为单个块来处理。你可以通过()来建立一个组。输入字符中匹配捕获组的部分将会被内存缓存并且可以通过向后引用来实现recall。

You can use matcher.groupCount method to find out the number of capturing groups in a regex pattern. For example in ((a)(bc)) contains 3 capturing groups; ((a)(bc)), (a) and (bc) .

你可以通过matcher.groupCount方法来找到匹配的捕获组个数。例如((a)(bc)) 包含了((a)(bc)), (a) and (bc) 这三种捕获组。

You can use Backreference in regular expression with backslash (\) and then the number of group to be recalled.

你可以通过在正则表达式中通过\和引用组的index来向后引用。(java 中\是转义字符,因此 \\来表示\)

Capturing groups and Backreferences can be confusing, so let’s understand this with an example.

捕获组以及向后引用很容易误解的,所以让我们通过例子来了解吧。

In the first example, at runtime first capturing group is (\w\d) which evaluates to “a2″ when matched with the input String “a2a2″ and saved in memory. So \1 is referring to “a2″ and hence it returns true.

在第一个例子中,运行时捕捉到了\\w\\d即字符+数字的组合的捕获组,字符串对应的是a2,于是将第一个捕获组a2存在内存中,于是\\1引用了第一个捕获组即"a2".于是第一个例子返回的是true。

Due to same reason second statement prints false. 同样的原因,第二个字符串,"b2" 并不符合第一个捕获组“a2”,于是false了。

Try to understand this scenario for statement 3 and 4 yourself.

自己理解例3、例4吧。同样的道理,向后引用引用的是前面的捕获组而不是正则表达式。



Now we will look at some important methods of Pattern and Matcher classes.

下面我们来看看类Pattern and Matcher中重要的方法把

We can create a Pattern object with flags. For example Pattern.CASE_INSENSITIVE enables case insensitive matching.

Pattern创建的时候可以自带flag,例如Pattern.CASE_INSENSITIVE大小写敏感。

Pattern class also provides split(String) that is similar to String class
split() method.

Pattern类的split(String)类似于String类的split()。

Pattern class toString() method returns the regular expression String from which this pattern was compiled.

Pattern的toString()方法返回的是pattern编译之后的正则表达式字符串

Pattern pattern = Pattern.compile("(\\w\\d)\\1", Pattern.CASE_INSENSITIVE);
System.out.println( pattern.toString() );

控制台输出 : (\w\d)\1

Matcher classes have start() and end() index methods that show precisely where the match was found in the input string.

Matcher 类的start() and
end()
精确的显示了匹配串的index。

Matcher class also provides String manipulation methods replaceAll(String replacement)
and replaceFirst(String replacement).

Matcher 类也有 replaceAll(String replacement) 和replaceFirst(String replacement).方法

Now we will see these common functions in action through a simple java class:

Output of the above program is:

Regular expressions are one of the area of
java interview questions and in next few posts, I will provide some real life examples.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 正则