A regular expression is a string of characters that defines/forms a pattern to search an input text. A regular expression may contain one or more characters, using a regular expression you can search or replace a string.
Java provides the java.util.regex package for pattern matching with regular expressions. This package contains three classes they are −
- Pattern class: The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely:
- compile(): This method accepts a String representing a regular expression and returns an object of the Pattern object.
- matcher(): This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.
- The Matcher class of java.util.regex package is an engine which performs match operations. To find the matched value this you need to use two methods of this class namely:
- find(): This method returns true if the match operation represented by the current object is successful else, it returns false.
- group(): This method accepts a integer value representing a particular group and returns the sequence captured by the specified group in the match operation.
- PatternSyntaxException− A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.
Example
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "[^\\p{ASCII}]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString() );
}
}Output
Enter input string: whÿ do we fall Result: wh do we fall
Example
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[t]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
int start = matcher.start();
System.out.println(start);
}
}
}Output
Enter input text: Hello how are you welcome to Tutorialspoint 26 31 42