gpt4 book ai didi

java - 仅当仅存在一位数字时,才在 Java 中删除字符串中的最后一位数字

转载 作者:行者123 更新时间:2023-12-04 09:16:12 26 4
gpt4 key购买 nike

我想删除 Java 字符串中的最后一位数字,前提是它只存在一位数字。
例如。

String text = "I am the9 number1"; // should be "I am the number"
什么都不做的情况:
String = "I913 am the55 number11"; // Should remain the same.
我试过这个没有成功:
String text = "I am the1 number1";
text = text.replaceAll("^[0-9]$", "");
没有工作。有什么帮助吗?

最佳答案

要替换字符串中的最后一位数字,您可以使用

text = text.replaceAll("\\B(?<!\\d)\\d\\b", "");
regex demo .
详情
  • \B - 一个字母或 _必须立即出现在当前位置的左侧
  • (?<!\d) - 如果当前位置左侧有一个数字,则匹配失败的负向后视
  • \d - 一个数字
  • \b - 一个字边界。

  • Java demo :
    String rx = "\\B(?<!\\d)\\d\\b";
    System.out.println("I am the number1".replaceAll(rx, ""));
    // => I am the number
    System.out.println("I am the number11".replaceAll(rx, ""));
    // => I am the number11
    System.out.println("I am 4the number1 @#@%$grtuy".replaceAll(rx, ""));
    // => I am 4the number @#@%$grtuy
    System.out.println("I am number1 1 and you number2 2".replaceAll(rx, ""));
    // => I am number 1 and you number 2

    关于java - 仅当仅存在一位数字时,才在 Java 中删除字符串中的最后一位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196787/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com