
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Named Captured Groups in Java Regular Expressions
Named capturing groups allows you to reference the groups by names. Java started supporting captured groups since SE7.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAll{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "(?<globalCode>[\d]{2})-(?<nationalCode>[\d]{5})-(?<number>[\d]{6})"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println("Global code: "+matcher.group("globalCode")); System.out.println("National code: "+matcher.group("nationalCode")); System.out.println("Phone number: "+matcher.group("number")); } } }
Output
Enter input text: 91-08955-224558 Global code: 91 National code: 08955 Phone number: 224558
Advertisements