英文:
Remove last digit in a string in Java only if it is just one digit present
问题
Here's the translation:
我想要在Java字符串中删除最后一个数字,只有当只有一个数字时才删除。
例如:
String text = "I am the9 number1"; // 应为 "I am the number"
不需要执行任何操作的情况:
String = "I913 am the55 number11"; // 保持不变。
我尝试了以下方法,但没有成功:
String text = "I am the1 number1";
text = text.replaceAll("^[0-9]$", "");
没有起作用。需要帮助吗?
英文:
I would like to remove last digit in a Java string, only if it is just one digit present.
E.g.
String text = "I am the9 number1"; // should be "I am the number"
Cases where it should do nothing:
String = "I913 am the55 number11"; // Should remain the same.
I tried this without success:
String text = "I am the1 number1";
text = text.replaceAll("^[0-9]$", "");
Didnt work. Any help?
答案1
得分: 1
要替换字符串中的最后一个数字,您可以使用以下代码:
text = text.replaceAll("B(?<!\\d)\\d\\b", "");
请参阅[正则表达式演示][1]。
**详细信息**
- `\B` - 必须在当前位置的左侧立即出现字母或下划线。
- `(?<!\d)` - 负向回顾先行,如果当前位置的左侧有数字,则匹配失败。
- `\d` - 数字
- `\b` - 单词边界。
[Java演示][2]:
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
[1]: https://regex101.com/r/D3y94p/3
[2]: https://ideone.com/MXtKFO
英文:
To replace the last digit in a string you may use
text = text.replaceAll("\\B(?<!\\d)\\d\\b", "");
See the regex demo.
Details
\B
- a letter or_
must appear immediately to the left of the current position(?<!\d)
- a negative lookbehind that fails the match if there is a digit immediately to the left of the current location\d
- a digit\b
- a word boundary.
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
答案2
得分: 1
你可以使用
(?<=[A-Za-z])\d(?!\\d)
详情
(?<=[A-Za-z])
:表示匹配数字前面是单词字符的正向后查找。
\d
:表示数字。
(?!\\d)
:表示匹配的数字后面不能再有其他数字的负向前瞻。
示例代码
text = text.replaceAll("(?<=[A-Za-z])\\d(?!\\d)", "");
英文:
You can use
(?<=[A-Za-z])\d(?!\d)
Details
(?<=[A-Za-z])
: it indicates word character before digit as positive lookbehind
\d
: indicates number
(?!\d)
: there has to be no other number after matched number (negative lookahead)
Sample Code
text = text.replaceAll("(?<=[A-Za-z])\d(?!\d)", "");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论