dynamitem
dynamitem

Reputation: 1669

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?

Upvotes: 0

Views: 90

Answers (2)

drxl
drxl

Reputation: 364

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.

Upvotes: 0

Matt Coats
Matt Coats

Reputation: 332

Is your goal to match all three of those cases?

If so, this should work: img\/s\/\d+x\d+\/

It searches for img/s/[1 or more digits]x[1 or more digits]/

Upvotes: 1

Related Questions