2015年3月10日 星期二

[ Java 文章收集 ] Backreferences in Java Regular Expressions

Source From HerePrefaceBackreferences in Java Regular Expressions is another important feature provided by Java.

To understand backreferences, we need to understand group first. Group in regular expression means treating multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses - ”()”. Each set of parentheses corresponds to a group.

Backreferences are convenient, because it allows us to repeat a pattern without writing it again. We can just refer to the previous defined group by using \# (# is the group number). This will make more sense after you read the following two examples.

Example 1: Finding Repeated Pattern(\d\d\d)\1 matches 123123, but does not match 123456 in a row. This indicates that the referred pattern needs to be exactly the name. Below is the sample code:

Example 2: Finding Duplicate WordsBelow sample code will help to find duplicate word in a sequence. However, this is not a good method to use regular expression to find duplicate words. From the example above, the first “duplicate” is not matched.