Java regular expressions are used for text manipulation tasks, including validating input (such as email addresses), extracting data (such as integers), replacing text, splitting strings, finding matches, and creating custom matchers.
Usage of Java regular expressions
Regular expressions (regex) are powerful pattern matching tools. It can be used for various text manipulation tasks in Java. Its usage is extensive, including:
1. Verify input
String email = "example@example.com"; boolean isValid = email.matches("^[a-zA-Z0-9.!#$%&'* /=?^_
{|}~-] @[a-zA-Z0-9]( ?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA- Z0-9-]{0,61}[a-zA-Z0-9])?)*$");`2. Extract data
String text = "The number is 123"; int number = Integer.parseInt(text.replaceAll("[^\\d]", "")) ;
3. Replace text
String text = "123abc456 "; text = text.replaceAll("[0-9]", "X");
4. Split the string
String[] tokens = text.split(",");
5. Find matches
List<String> matches = Files.lines(Paths.get("file.txt")).filter(line -> line.startsWith("PATTERN")).toList();
#6. Custom matcher
Predicate<String> isPhoneNumber = Pattern.matches("^\\(\\d{3}\\) \\d{3}-\\d{4}$") ;
Syntax
The regular expression syntax is based on the following notation:
Use Tip
The above is the detailed content of What are the uses of regular expressions in java. For more information, please follow other related articles on the PHP Chinese website!