lundi 24 février 2020

How to match all combinations of numbers in a string that do not start with an English letter in regular matching in Java

I have a String like

String str = "305556710S  or 100596269C OR CN111111111";

I just want to match the characters in this string that start with numbers or start with numbers and end with English letters, Then prefix the matched characters add with two "??" characters. I write a Patern like

    Pattern pattern = Pattern.compile("^[0-9]{1,10}[A-Z]{0,1}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        String matchStr = matcher.group();
        System.err.println(matchStr);
    }

But it can only match the first character "305556710S". But If I modify the Pattern

 Pattern pattern = Pattern.compile("[0-9]{1,10}[A-Z]{0,1}", Pattern.CASE_INSENSITIVE);

It will matches "305556710S","100596269C","111111111".But the prefix of "111111111" is English character "CN" which is not my goal. I only want match the "305556710S" and "100596269C" and add two "??" characters before the matched Characters.Can somebody help me ?

Aucun commentaire:

Enregistrer un commentaire