kwbock
kwbock

Reputation: 647

Capture group that captures an entire string minus a section that matches a pattern

I'm not sure if this is possible, but I figured I'd ask anyways. What I need to do is effectively create a search/replace, but without using the regex s/pattern1/pattern2/ syntax as it is not directly exposed to me.

Is it possible to create a capture group that would take an image path, with the image size before the extension and remove the image size.

For instance convert http://example.com/path/to/image/filename-200x200.jpg to http://example.com/path/to/image/filename.jpg using only a capture group and no search/replace bits.

I'm asking as the software I'm working in does not currently have a search/replace functionality.

Upvotes: 0

Views: 33

Answers (1)

UnlimitedHighground
UnlimitedHighground

Reputation: 760

It's somewhat possible. There's no built-in capability for a match to be something other than a continuous segment of the source text, but you can work around that.

One approach you might consider is the use of non-capturing groups and concatenation. In regex, groups beginning with ?: aren't captured as matches.

For example, given the regex (A)(?:B)(C) and the string "ABC", the result would be:

1. "A"
2. "C"

In your case, then, you could capture around the part you want to ignore, then concatenate the parts you want.

Given the string you provided, http://example.com/path/to/image/filename-200x200.jpg, the regex (.+)(?:-200x200)(.+) returns:

1. "http://example.com/path/to/image/filename"
2. ".jpg"

You could then add the first and second capture groups to produce your intended result.

Upvotes: 1

Related Questions