Faheem Kalsekar
Faheem Kalsekar

Reputation: 1420

Regex: Find & Replace in String

I have a string

String customHtml = "<html><body><iframe src=https://zarabol.rediff.com/widget/end-of-cold-war-salman-hugs-abhishek-bachchan?search=true&header=true id=rediff_zarabol_widget name=rediff_zarabol_widget scrolling=auto transparency= frameborder=0 height=500 width=100%></iframe></body></html>";

I need to replace the last index of weburl with another string. In the above example replace

end-of-cold-war-salman-hugs-abhishek-bachchan

with

srk-confesses-found-gauri-to-be-physically-attractive

I tried using Lazy /begin.*?end/ but it fails. Any help will be highly appreciated. Thanks in advance.

Upvotes: 0

Views: 120

Answers (4)

Bohemian
Bohemian

Reputation: 425033

This should do it:

url = url.replaceAll("(?<=/)[^/?]+(?=\\?)", "your new text");

Upvotes: 1

zx81
zx81

Reputation: 41838

As others have said, a DOM parser would be better. For completion, here is a regex solution that will work for your input:

String replaced = yourString.replaceAll("(https://\\S+/)[^?]+", 
                    "$1srk-confesses-found-gauri-to-be-physically-attractive");

Explanation

  • (https://\\S+/) captures to Group 1 the literal https://, any chars that are not white-spaces \S+, and a forward slash /
  • [^?]+ matches any chars that are not ? (the text to replace)
  • We replace with $1 Group 1 (unchanged) and the text you specified

Upvotes: 0

user3440171
user3440171

Reputation: 21

Regex: [^/]*?(?:\?)

You must remove "/" from regex.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Regex:

(?<=\/)[^\/]*(?=\?)

Java regex:

(?<=/)[^/]*(?=\\?)

Replacement string:

srk-confesses-found-gauri-to-be-physically-attractive

DEMO

Java code would be,

String url= "<html><body><iframe src=https://zarabol.rediff.com/widget/end-of-cold-war-salman-hugs-abhishek-bachchan?search=true&header=true id=rediff_zarabol_widget name=rediff_zarabol_widget scrolling=auto transparency= frameborder=0 height=500 width=100%></iframe></body></html>";
String m1 = url.replaceAll("(?<=\\/)[^\\/]*(?=\\?)", "srk-confesses-found-gauri-to-be-physically-attractive");
System.out.println(m1);

IDEONE

Upvotes: 2

Related Questions