1024programmer Java Java regular expression study notes named capture

Java regular expression study notes named capture

Many regular engines support named groups. Java only introduced this feature in Java 7. The syntax is similar to .Net (.Net allows groups with the same name to appear in the same expression, but java does not).
Naming groups is easy to understand, which is to name the groups. The following is a brief demonstration of how to use and precautions in java.

1. Define a group named NAME in the regular expression
(?X)
Here X is the content we want to match. Note that the name cannot be repeated, and the name cannot start with a number!

2. The content matched by the reverse reference NAME group
\k
Note that the backreference is to the content matched by the group, not the expression of the group.

3. During replacement, reference the string captured in group NAME
${NAME}

4. Get the string captured by the NAME group
group(String NAME)
Note: You can also use serial numbers to reference named captures. The serial numbers start from 1, and 0 is the complete matching result of the regular expression.

The following uses a simple regular rule to obtain the year, month and day respectively as an example:

 String s = "2015-10-26";
 Pattern p = Pattern.compile("(?\\d{4})-(?\\d{2})-(?\\  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
   System.out.println("month: " + m.group(2)); //The second group
   System.out.println("day: " + m.group(3)); //The third group
 }
 
 System.out.println(s.replaceAll("(?\\d{4})-(?\\d{2})-(?\\d{2})", "${day}-${month}-${year}")); //Change the date in year-month-day format to 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 it will be helpful to everyone’s study.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/703498

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索