【问题标题】:Dynamic incrementation of all numbers within a String [duplicate]字符串中所有数字的动态递增[重复]
【发布时间】:2017-02-22 17:11:28
【问题描述】:

除了使用匹配器获取数字,将其加一并替换之外,是否有任何 Java 解决方案可以替换字符串中的数字?

“REPEAT_FOR_4”将返回“REPEAT_FOR_5” “REPEAT_FOR_10”将返回“REPEAT_FOR_11”

我想在一行中使用正则表达式并替换,而不是通过将字符串重新组合为“REPEAT_FOR_”并在递增后添加数字。 谢谢!

稍后编辑:我想知道如何将字符串中的数字替换为以下数字。

【问题讨论】:

  • 是的,Matcher#appendReplacement
  • 从技术上讲,您不能“替换”String 中的任何内容,因为String 的对象是不可变的。但是您可以创建一个新的String,其中包含旧前缀加上 Integer.valueOf(suffix) + 1。
  • 是的,我知道。我会更新我的问题。生成一个新字符串 :)
  • 您可以使用 IntStream,将其映射到 Integer,然后在一行代码中生成字符串列表。
  • 谢谢,帕夫尼特!很抱歉重复了这些问题。

标签: java regex string replace matcher


【解决方案1】:

我没有使用正则表达式,但这是一行中的解决方案。考虑到您的字符串保持不变。

public String getIncrementedString (String str){
return ("REPEAT_FOR_" + (Character.getNumericValue(str.charAt(11))+1));
}

【讨论】:

  • OP 说:不是通过将字符串重新组合为“REPEAT_FOR_”并在递增后添加数字
  • 但他的问题似乎是他想在一行中完成。
【解决方案2】:

是的,当然有可能。使用正则表达式 PatternMatcher,您需要执行以下操作:

    String str = "REPEAT_FOR_4";
    Pattern p = Pattern.compile("([0-9]+)");
    Matcher m = p.matcher(str);
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(1+ Integer.parseInt(m.group(1))));
    String updated = s.toString();
    System.out.println(updated);

这是 a working Example,它返回 REPEAT_FOR_5 作为输出。

【讨论】:

    【解决方案3】:

    你可以试试这个。

    String ss = "REPEAT_FOR_4";
    int vd = Integer.valueOf(ss.substring(ss.length() - 1));
    String nss = ss.replaceAll("\\d",String.valueOf(vd+1));
    
    System.out.println(nss);
    

    输出:

    REPEAT_FOR_5

    使用正则表达式:如果数字不在字符串的末尾。

        String ss = "REPEAT_5_FOR_ME";
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(ss);
        m.find();
        String strb = m.group();
        int vd = Integer.valueOf(strb);
        String nss = ss.replaceAll("\\d",String.valueOf(vd+1));
    
        System.out.println(nss);
    

    输出:

    REPEAT_6_FOR_ME

    基于 cmets cmets 中提出的问题,我认为此正则表达式解决方案会有所帮助。

    public static String convStr(String str){
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(str);
        m.find();
        String strb = m.group();
        int vd = Integer.valueOf(strb);
        return str.replaceAll("\\d",String.valueOf(vd+1));
      }
    

    【讨论】:

    • 但是如果数字不在字符串的末尾,那就不行了。我想出了这个解决方案: String nrToBeReplaced = CharMatcher.DIGIT.retainFrom(value); int nextNr = Integer.valueOf(nrToBeReplaced) + 1; return value.replaceAll(value, String.valueOf(nextNr));
    • @rianna 我已经用正则表达式更新了我的答案,它解决了你提出的问题
    猜你喜欢
    • 2015-08-28
    • 2018-12-01
    • 2013-04-24
    • 2011-11-22
    • 2013-04-11
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多