【问题标题】:How to replace every whitespace between 2 numbers?如何替换两个数字之间的每个空格?
【发布时间】:2019-06-11 08:04:24
【问题描述】:

我正在编写一个程序来获取字符串的不同部分,例如“10 万亿 8370 亿 4500 万 56739”。我问了这个问题here。 但有时我的字符串会变成“10 万亿 8370 亿 4500 万 56 739”。 我想删除“56 739”中 6 到 7 之间的空格。

我知道要删除空格,但不知道如何指定哪些字符是要删除的空格

这是我的代码

String input = "10 trillion 837 billion 45 million 56 739";
                String pattern = "\\s\\d";     // this will match space and number thus will give you start of each number.
                ArrayList<Integer> inds = new ArrayList<Integer>();
                ArrayList<String> strs = new ArrayList<String>();
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(input);
                while (m.find()) {
                    inds.add(m.start());          //start will return starting index.
                }

                //iterate over start indexes and each entry in inds array list will be the end index of substring.
                //start index will be 0 and for subsequent iterations it will be end index + 1th position.
                int indx = 0;
                for(int i=0; i <= inds.size(); i++) {
                    if(i < inds.size()) {
                        strs.add(input.substring(indx, inds.get(i)));
                        indx = inds.get(i)+1;
                    } else {
                        strs.add(input.substring(indx, input.length()));
                    }
                }

                for(int i =0; i < strs.size(); i++) {
                    Toast.makeText(getApplicationContext(),strs.get(i)+"",Toast.LENGTH_LONG).show();
                }


我尝试添加这样的 replaceAll 语句input = input.replaceAll("\\d\\s\\d","\\d\\d"); 但它不起作用

【问题讨论】:

    标签: java regex replace


    【解决方案1】:

    我发现(或假设)是您试图删除 string 中数字之间的空格,所以,

    您可以使用此regex 替换数字之间的space

    (?&lt;=\\d)\\s+(?=\\d|\\-)点赞:

    input = input.replaceAll("(?<=\\d)\\s+(?=\\d|\\-)", "");
    

    (?&lt;=\d) 是一个正向的lookbehind,它检查前一个符号是否是一个数字,而不实际匹配它。

    (?=\d) 是一个正向的前瞻,同样的事情 - 检查下面的符号是否是一个数字,而不是实际匹配它。

    您可以在这里测试正则表达式: https://regex101.com/r/pdEoKO/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2016-03-06
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      相关资源
      最近更新 更多