A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern.
The capturing groups in regular expressions are used to treat multiple characters as a single unit it is represented by “()”. i.e. if you place multiple sub patterns with in a parathesis they are treated as one group.
For example, the pattern [0-9] matches the digits 0 to 9 and the pattern {5} matches any characters. If you group these two as ([0-9]{5}), it matches a 5-digit number.
Example
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your Date of birth: ");
String dob = sc.nextLine();
//Regular expression to accept date in MM-DD-YYY format
String regex = "^(1[0-2]|0[1-9])/ # For Month\n"
+ "(3[01]|[12][0-9]|0[1-9])/ # For Date\n"
+ "[0-9]{4}$ # For Year";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//Creating a Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if(result) {
System.out.println("Given date of birth is valid");
}else {
System.out.println("Given date of birth is not valid");
}
}
}Output
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("match: "+matcher.group(0));
System.out.println("First group match: "+matcher.group(1));
System.out.println("Second group match: "+matcher.group(2));
System.out.println("Third group match: "+matcher.group(3));
}
}
}Output
match: This is a sample Text, 1234, with numbers in between. First group match: This is a sample Text, 123 Second group match: 4 Third group match: , with numbers in between.