java - How to replace a number from a text which is not appended to a string
问题描述
I want to replace the number 123 from the below string, but the challenge I am facing is - everytime I replace it, then the number i.e, 1 from name "Xyz1" also got changed. Below is a sample code which I already tried:
import java.util.*;
import java.lang.*;
import java.io.*;
class NumberToString
{
public static void main (String[] args) throws java.lang.Exception
{
String str = "Hello Xyz1, your id is 123";
// str = str.replaceAll("[0-9]","idNew");
// str = str.replaceAll("\\d","idNew");
// str = str.replaceAll("\\d+","idNew");
str = str.replaceAll("(?>-?\\d+(?:[\\./]\\d+)?)","idNew");
System.out.println(str);
}
}
Output of the above code is: Hello XyzidNew, your id is idNew
But, the output which I need is: Hello Xyz1, your id is idNew
解决方案
如果您使用正则表达式\d+$
,您将获得预期的输出。例子:
public static void main (String[] args) throws java.lang.Exception
{
String str = "Hello Xyz1, your id is 123";
str = str.replaceAll("\\d+$","idNew");
System.out.println(str);
// Variation without the end of line boundary matcher
System.out.println("Hello Xyz1, your id is 123.".replaceAll("\\b\\d+(?![0-9])","idNew"));
}
\d+$
- 此正则表达式匹配多个数字,后跟行尾。
推荐阅读
- dart - 测试使用插件和平台通道的 Flutter 代码
- c# - 异步删除显示数据的问题
- .net-core - EF Core 引用同一张表,单个集合
- reactjs - 在无状态组件中获取 ref
- javascript - 与 ng-options 中的硬编码 json 相比,解析我的动态 json 时出错
- google-cloud-platform - 如何在没有 ?authuser=1 的情况下获得经过身份验证的 GCS URL
- swift - 运行应用程序时,表格视图单元上未显示 Swift 按钮
- amazon-web-services - AWS Classic Load Balancer 随机不接收请求
- python - 用于单词计数、平均单词长度、单词频率和以字母开头的单词频率的 Python 程序
- android - (Mockito + Kotlin) Android 测试中的 eq() 和 any() 返回 null