📅  最后修改于: 2023-12-03 15:38:33.941000             🧑  作者: Mango
在Java中,可以使用正则表达式来匹配字符串中的区域。以下是一些常用的方法:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
String patternStr = "([A-Za-z]+) ([0-9]+)";
String inputStr = "Java 123 is great.";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
System.out.println(matcher.group(1)); // 输出Java
System.out.println(matcher.group(2)); // 输出123
}
}
}
解释:
public class RegexTest {
public static void main(String[] args) {
String pattern = "[A-Za-z]+";
String input = "Java is great";
boolean matches = input.matches(pattern);
System.out.println(matches); // 输出true
}
}
解释:
public class RegexTest {
public static void main(String[] args) {
String pattern = "\\s+";
String input = "Java is great";
String[] words = input.split(pattern);
for (String word : words) {
System.out.println(word);
}
}
}
解释: