English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Subexpression/The meta-character "()" groups the regular expression and remembers the matched text.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example {}} public static void main(String[] args) { String input = "Hello how are you welcome to w3codebox" String regex = "H(ell|ow)"; //Compile the regular expression Pattern pattern = Pattern.compile(regex); //Retrieve the matcher object Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
Output result
Match found
In the following example, we try to match sentences that contain numbers-
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { System.out.println("Enter input string:"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Use regular expression with groups String regex = "(?:*);+);*); //Create a pattern object Pattern pattern = Pattern.compile(regex); //Create a Matcher object Matcher matcher = pattern.matcher(input); boolean bool = matcher.matches(); if(bool) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
Output result
Enter input string: This is a 5363 test string Match found