简体   繁体   中英

Java String::replaceAll only replaces first occurrence (probably incorrect regex)

I'm trying to retrieve some page from confluence and render it inside my own application. I'm using regex to replace confluence image urls with my endpoints that provides authenticated proxy between confluence and my app's user.

regex is:

(src|href)="\/download\/(.*)\/(.*)\/(.*)

and whole replacement line is:

html = html.replaceAll("(src|href)=\"\\/download\\/(.*)\\/(.*)\\/(.*)", "$1=\"" + baseUrl + "/rest/myapp/documents/"+instance+"/$2/$3/$4");

I'm trying to replace

src="/download/attachments/65591/ with src="https://myapp/rest/myapp/documents/{instance}/thumbnails/65591/

I tested this regex using different tools, including https://regex101.com/r/8r77OF/4 but while my test results are positive, my application only replaces the first occurrence.

What am I doing wrong?

As matt suggested, .* is greedy so replacing my regex with

"(src|href)=\"\\/download\\/(.*?)\\/(.*?)\\/(.*?)\\/"

solved the problem. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM