Summary of common Java regular expression methods
Regular expression is a powerful tool for matching, finding and replacing strings, which has been introduced in Java Wide range of applications. This article will summarize some commonly used regular expression methods in Java and provide specific code examples.
Sample code:
String regex = "a*b"; String input = "aab"; boolean isMatched = input.matches(regex); System.out.println(isMatched); // 输出true
Sample code:
String regex = "\d+"; String input = "123abc456def"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); // 输出123、456 }
Sample code:
String regex = "\d+"; String input = "123abc456def"; String replacement = "X"; String output = input.replaceAll(regex, replacement); System.out.println(output); // 输出XabcXdef
Sample code:
String regex = "[,.\s]+"; String input = "Java,Python,C++,JavaScript"; String[] output = input.split(regex); for (String word : output) { System.out.println(word); // 输出Java、Python、C++、JavaScript }
Sample code:
String regex = "(\d+)([a-zA-Z]+)"; String input = "123abc456def"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { // 输出整个字符串 System.out.println(matcher.group(0)); // 输出123abc456def // 输出第一个分组 System.out.println(matcher.group(1)); // 输出123 // 输出第二个分组 System.out.println(matcher.group(2)); // 输出abc }
The above is a summary and code examples of common methods of Java regular expressions. Mastering these methods can help us handle string matching, search, and replacement tasks more conveniently and efficiently, and improve development efficiency. Of course, the syntax of regular expressions is very rich and complex, and needs to be learned and applied according to specific needs.
The above is the detailed content of Summary of common Java regular expression methods. For more information, please follow other related articles on the PHP Chinese website!