【问题标题】:I want to replace the second occurrence of the number in the string我想替换字符串中第二次出现的数字
【发布时间】:2016-07-24 21:23:02
【问题描述】:

我有一个字符串,如下所示的网址

"www.regexperl.com/1234/34/firstpage/home.php"

现在我需要将字符串中第二次出现的数字 34 替换为 2。

结果字符串应该是这样的

"www.regexperl.com/1234/2/firstpage/home.php"

我面临的挑战是当我尝试存储值 34 并替换它时,它正在替换数字 1234 中的 34 并给出如下结果

"www.regexperl.com/122/34/firstpage/home.php"

请告诉我一个合适的正则表达式来解决问题。

【问题讨论】:

  • 这个数字的位置是不变的吗?我的意思是在第一个斜线和第二个斜线之后?
  • 或正则表达式:^(\D*\d+\D*)\d+ 替换为\12
  • 它不特定于 34,它可以是任何数字。我只是在这里举了一个例子 34
  • 是的用户(菜鸟)的位置是恒定的.. 像 /number/number/word

标签: regex string perl replace


【解决方案1】:

使用\K

^.*?\d+\b.*?\K\d+

替换为your string。查看演示。

https://regex101.com/r/lW2kK1/1

【讨论】:

    【解决方案2】:

    好吧,如果位置不变,那么你可以找到并替换如下。

    正则表达式: (\.com\/\d+)(\/\d+)

    输入字符串: www.regexperl.com/1234/34/firstpage/home.php

    替换为:替换为\1/,后跟您选择的数字。例如\1/2

    输出字符串: www.regexperl.com/1234/2/firstpage/home.php

    Regex101 Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2022-10-07
      • 2014-02-13
      相关资源
      最近更新 更多