我想替换字符串中第二次出现的数字

时间:2016-04-05 05:29:38

标签: regex string perl replace

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

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

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

结果字符串应该像

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

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

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

请让我知道正确的正则表达式来解决问题。

2 个答案:

答案 0 :(得分:1)

使用// call the Chrome driver as below first System.setProperty("webdriver.chrome.driver", "D:\\eclipseProject\\##\\src\\com\\##\\chromedriver_win32\\chromedriver.exe"); // path to chrome exe that you have downloaded form given url (below) driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://www.seleniumhq.com"); // link to your web-table web page

\K

替换为^.*?\d+\b.*?\K\d+ 。请参阅演示。

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

答案 1 :(得分:0)

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

正则表达式: class Testimony implements Parcelable { private String testimony; private String name; private int id; public Testimony(String testimony,String name, int id){ this.testimony = testimony; this.id = id; this.name = name; } protected Testimony(Parcel in) { testimony = in.readString(); name = in.readString(); id = in.readInt(); } public String gettestimony() { return testimony; } public String getname() { return name; } public int getid() { return id; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(testimony); dest.writeString(name); dest.writeInt(id); } public static final Creator<Image> CREATOR = new Creator<Image>() { @Override public Image createFromParcel(Parcel in) { return new Image(in); } @Override public Image[] newArray(int size) { return new Image[size]; } }; }

输入字符串: (\.com\/\d+)(\/\d+)

替换为:替换为www.regexperl.com/1234/34/firstpage/home.php,后跟您选择的号码。例如\1/

输出字符串: \1/2

Regex101 Demo