core_m core_m - 4 months ago 8
Java Question

Replace string part with regex pattern

I would like to replace the following string.

img/s/430x250/


The problem is there are variations, like:

img/s/265x200/


or:

img/s/110x73/


So I would like to replace this part in whole, but the numbers are changeable, so how could I make a pattern that replaces it from a string?

Answer

This regular expression will match your examples

img\/s\/\d+?x\d+?\/

the / matches / the \d matches digits 0-9 and the + means 1 or more. The ? makes it lazy instead of greedy.

the img and s just match that literally

check out https://regex101.com/ to try out regular expressions. It's much easier than testing them by debugging code. Once you find an expression that works, you can move on to make sure your specific code will perform the same.