I want to replace the second occurrence of the num

2019-07-10 03:06发布

I have a string say a url like below

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

Now i need to replace the 34 number that is the second occurrence of a number in the string with 2.

The resultant string should be like

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

The challenge I m facing is when i try to store the value 34 and replace it , It is replacing the 34 in the number 1234 and gives the result like below

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

Kindly let me know a proper regex to solve the problem.

2条回答
闹够了就滚
2楼-- · 2019-07-10 03:22

Well if the positions are constant then you can find and replace as follows.

Regex: (\.com\/\d+)(\/\d+)

Input string: www.regexperl.com/1234/34/firstpage/home.php

Replacement to do: Replace with \1/ followed by number of your choice. For example \1/2.

Output string: www.regexperl.com/1234/2/firstpage/home.php

Regex101 Demo

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-10 03:24

Use \K.

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

Replace by your string.See demo.

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

查看更多
登录 后发表回答