climbbikecode
climbbikecode

Reputation: 11

Write a regex to match until the final forward slash before the first equal sign

Here's a fun regex problem. Write one regex that will get the results for group one as "path/to/file" for the following example strings:

  1. path/to/file/foo=1/bar.txt
  2. path/to/file/foo=1/bar=2/baz.txt
  3. path/to/file/foo.txt

So to explain, I want to match up to the final forward slash before the first occurrence of an '='.

I was able to match a regex with the example string one (^.*)\/(.*)= but it captures path/to/file/foo=1 from example string 2 -- this is not as intended, I do not want to see the part of the path with the '='.

I can use (^.*)\/(.*)=(.*)= to solve example 2, but this doesn't scale to the other examples.

Example 3 is easy enough to capture with (^.*)\/ Being able to match string 3 is a nice to have, but I have a way of easily solving for this in my code.

Thanks for your help and I look forward to learning more about regex.

Upvotes: 0

Views: 198

Answers (1)

Silvanas
Silvanas

Reputation: 613

You should use this regex,

^([^=]+)\/

This will match everything except = and will stop the match as soon as it finds a / and will capture the contents in group one as you want.

Check this demo

Upvotes: 1

Related Questions