如何替换这个
String str = "KMMH12DE1433";
String pattern = "^[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})$";
String str2 = str.replaceAll(pattern, "repl");
Log.e("Founded_words2",str2);
我得到的是:KMMH12DE1433
我想要的是:MH12DE1433
最佳答案
使用正确的 java.util.regex.Pattern
和 java.util.regex.Matcher
尝试这样的操作:
String str = "KMMH12DE1433";
//Make the pattern, case-insensitive using (?i)
Pattern pattern = Pattern.compile("(?i)[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})");
//Create the Matcher
Matcher m = pattern.matcher(str);
//Check if we find anything
if(m.find()) {
//Use what you found - with proper capturing groups you
//gain access to parts of your pattern as needed
System.out.println("Found this: " + m.group());
}
关于java - 我该如何更换这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127205/