Java Regular Expression Learning notes named Capture _java

Source: Internet
Author: User

Many regular engines support named groupings, and Java is introduced in Java7, syntax and. NET similar (. NET allows the same expression to appear with the same name as the same group, Java is not allowed).
A named grouping is a good idea to name a group. Here's a quick example of how to use Java and considerations.

1. Define a group named name in regular
(? <name>x)
Here x for us to match the content, note that in this name can not be repeated, the name can not begin with the number!

2. Reverse reference to what the name group matches
\k<name>
Note that the reverse reference is what the group matches, not the group's expression.

3. In substitution, reference to the string captured in group name
${name}

4. Gets the string that the name group captures
Group (String NAME)
Note: You can also use ordinal to reference named captures, with ordinal numbers starting at 1, and 0 as the full matching result of a regular.

The following is a simple regular to obtain the month and year as an example:

String s = "2015-10-26"; 
Pattern p = pattern.compile ("(? <year>\\d{4})-(? <month>\\d{2})-(? <day>\\d{2})"); 
Matcher m = P.matcher (s); 
if (M.find ()) { 
  System.out.println ("Year:" + M.group ("year")); Year 
  System.out.println ("Month:" + m.group ("month")); Month 
  System.out.println ("Day:" + m.group ("Day")); Day 
    
  System.out.println ("Year:" + m.group (1)); The first group of 
  System.out.println ("Month:" + m.group (2)); The second group of 
  System.out.println ("Day:" + m.group (3)); Group III 
} 
 
System.out.println (S.replaceall (? <year>\\d{4})-(? <month>\\d{2})-(? <day>\ \D{2}) "," ${day}-${month}-${year} "); Change the year-month-day form to the day-month-year format 

Output results

year:2015
month:10
day:26
year:2015
month:10
day:26
26-10-2015

The above is the entire content of this article, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.