我该如何替换它?

时间:2018-03-06 09:15:59

标签: java android

如何替换此

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

4 个答案:

答案 0 :(得分:1)

使用正确的java.util.regex.Patternjava.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());
    }

答案 1 :(得分:0)

如果您只想删除前两个字符,前两个字符将始终为大写字母:

String str = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String str2 = str.replaceAll(pattern, "");
Log.e("Output string: ", str2);

答案 2 :(得分:0)

试试这个:

    String a = "KMMH12DE1433";
    String pattern = "^[A-Z]{2}";
    String rs = a.replaceAll(pattern,"");

答案 3 :(得分:0)

请改变这样

String ans=str.substring(0);