【问题标题】:String regular expression java字符串正则表达式 java
【发布时间】:2014-12-01 10:56:35
【问题描述】:

我正在开发一个有此要求的实用程序:

  1. 有一个包含参数的字符串,例如 -@p1 或 @p2 或 @pn,其中 n 可以是任意数字。

例如字符串是:

输入:

它提供@p1 最新消息、来自印度的@p2 和@p3 世界的视频。从@p5 Business,@p5

获取今天的新闻头条
  1. 用@pn@ 替换所有参数。所以如果参数是@p1,它会变成@p1@。

上面的字符串会变成:

输出:

它提供@p1@ 最新消息、来自印度的@p2@ 和@p3@ 世界的视频。从@p4@ Business、@p5@

获取今天的新闻头条

任何快速帮助表示赞赏。

谢谢。

【问题讨论】:

    标签: java regex string


    【解决方案1】:

    使用string.replaceAll 函数,如下所示。

    string.replaceAll("(@p\\d+)", "$1@");
    

    \d+ 匹配一位或多位数字。 () 称为捕获组,它捕获与() 内部的模式匹配的字符,并将捕获的字符存储到相应的组中。稍后我们可以通过指定其索引来引用这些字符,例如 $1$2

    例子:

    String s = "It provides @p1 latest news, videos @p2 from India and @p3 the world. Get today's news headlines from @p5 Business, @p5";
    System.out.println(s.replaceAll("(@p\\d+)", "$1@"));
    

    输出:

    It provides @p1@ latest news, videos @p2@ from India and @p3@ the world. Get today's news headlines from @p5@ Business, @p5@
    

    【讨论】:

      【解决方案2】:

      你可以试试这样的正则表达式:

      public static void main(String[] args) {
          String s = "it provides @p1 latest news, videos @p2 from India and @p3 the world. Get today's news headlines from @p5 Business, @p5";
          System.out.println(s.replaceAll("(@p\\d+)(?=\\s+|$)", "$1\\@"));
      }
      

      O/P:

      it provides @p1@ latest news, videos @p2@ from India and @p3@ the world. Get today's news headlines from @p5@ Business, @p5@
      

      解释:

      (@p\\d+)(?=\\s+|$) --> `@p` followed by any number of digits (which are all captured) followed by a space or end of String (which are matched but not captured..)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2011-12-29
        • 2023-03-22
        • 2013-10-14
        相关资源
        最近更新 更多