【问题标题】:How to replace a number from a text which is not appended to a string [duplicate]如何从未附加到字符串的文本中替换数字[重复]
【发布时间】:2018-12-17 21:38:12
【问题描述】:

我想从下面的字符串中替换数字 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

【问题讨论】:

  • Xyz1 可以包含多少个数字,id 是多长?
  • 使用单词边界,"(?>-?\\b\\d+(?:[\\./]\\d+)?)\\b" 或更简单的"-?\\b\\d+(?:[./]\\d+)?\\b"
  • Xyz1 最多可以包含 7 个数字,id 的最大长度为 10。

标签: java regex string


【解决方案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+$ - 此正则表达式匹配多个数字,后跟行尾。

【讨论】:

  • 谢谢!!有效。我刚刚尝试过,它适用于这种情况,但是如果我们在 123 之后添加一个新字符串,那么在这种情况下,整个正则表达式都会失败。有什么建议吗??
  • @PraveenKishor 检查不使用行尾边界匹配器的更新答案中的变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2017-04-03
  • 2021-03-26
  • 2019-04-03
  • 2020-10-21
  • 2013-05-18
相关资源
最近更新 更多