我想替换下面字符串中的数字 123,但我面临的挑战是 - 每次替换它时,名称“Xyz1”中的数字(即 1)也会更改。下面是我已经尝试过的示例代码:
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);
}
}
上述代码的输出为: 您好 XyzidNew,您的 ID 是 idNew
但是,我需要的输出是: 你好 Xyz1,你的 ID 是 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+$
- 此正则表达式匹配多个数字,后跟行尾。
关于java - 如何替换未附加到字符串的文本中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258487/