我想替换下面字符串中的数字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
答案 0 :(得分:1)
如果使用正则表达式\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+$
-此正则表达式匹配多个数字,后跟行尾。