Android - 如何替换此类字符串中的数字?

Android - How can I replace the number in this type of string?

有谁知道如何替换此类字符串中的数字并删除第二部分(如果存在)?

我知道这听起来很奇怪,让我解释一下。

每次处理的字符串都不一样:

号码(我需要更换的)可以从1位到10位,从:0到:9999999999(也可以为零 0000000000).

数字前总是有一个字符(可以是任何字符,任何大小写),如:X0000a00h000000G000.

有时后面可能会有另一部分(以连字符开头,如果存在我需要删除这部分),例如:X000-X00000X0000-X00X00-X0.

有时后面可能会有另一个额外的字符(可以是任何字符,任何大小写,以连字符开头,如果存在我需要保留这部分),例如:X00000-XX0000-X000-X , a000-h, g00000-j00-Y.

我不知道如何替换第一部分(如果存在),删除第二部分(如果存在)并保留最后一部分(如果存在),这是我需要的示例:

X0000 > X1234
a00 > a12
h000000 > h123456
G000 > G123

X000-X000000 > X123  -  replace the first and delete the last
X0000-X000 > X1234 -  replace the first and delete the last
X00-X00 > X12 -  replace the first and delete the last

X00000-X > X12345-X -  replace only the first and keep the last
a000-h > a123-h -  replace it and keep the last

X0000-X000-X > X1234-X -  replace the first, delete the second and keep the last
g00000-j00-Y > g12345-Y -  replace the first, delete the second and keep the last

在这个例子中,我主要使用 0 和 X,但正如所解释的,可以是 0 或任何数字,也可以是 X 或任何字符(大写或小写)。

编辑:忘了说,我需要得到那个数字,用它做一个数学运算然后替换它,不仅仅是替换。

有人知道怎么做吗?非常感谢。

一种方法是使用 replace()substring() 来实现,如下所示:

public static void main (String[] args) throws Exception {
    String input = "X000-X";
    String replacement = "123";
    int ls = input.lastIndexOf("-");
    int fs = input.indexOf("-");
    System.out.println("Extracted Number: " + (fs < 1 ? input.substring(1) : 
                                                        input.substring(1,fs)));
    System.out.println("Final Output: " + input.substring(0,1) + replacement + 
                       (ls != fs || fs == input.length() - 2 ? input.substring(ls) : ""));
}

输出:

Extracted Number: 000
Final Output: X123-X

我只会给你一个例子,你可以按照要求按照相同的方式进行操作,或者你可以根据你的要求将一些行分成单独的方法,

   String value = "X000-X000000";
    if(value.contains("-")){
        String match="";
        String[] elements = value.split("-");

        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher matcher = pattern.matcher(elements[0]); //For the first element that is X000

        while (matcher.find()) {
            match = matcher.group(); //Numeric is match that is 000
        }

    //Do whatever you want to do with 000 here like I replaced 123 here

     elements[0] = elements[0].replace(match, String.valueOf(123));
        StringBuilder builder = new StringBuilder();
        for(String s : elements) {
            builder.append(s + "-");
        }
        value = builder.toString().substring(0,builder.length()-1); //Your final value that can be returned as well


    }