Jannik
Jannik

Reputation: 5

Regex match 10 characters after second pattern

I would like to match 10 characters after the second pattern:

My String:

www.mysite.de/ep/3423141549/ep/B104RHWZZZ?something

What I want to be matched:

B104RHWZZZ

What the regex currently matches:

B104RHWZZZ?something

Currently, my Regex looks like this:

(?<=\/ep\/)(?:(?!\/ep\/).)*$.

Could someone help me to change the regex that it only matches 10 characters after the second "/ep/" ("B104RHWZZZ")?

Upvotes: 0

Views: 669

Answers (2)

Marty
Marty

Reputation: 1151

This would match the string as matching group 1: ep\/\w+\/ep\/(\w+)

https://regex101.com/r/9tUjxG/1

While lookarounds can make this expression more sophisticated so that you won't require matching groups, it makes (in my experiences) the expression hard to read, understand and maintain/extend.
That's why I would always keep regexes as simple as possible.

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163257

It depends on which characters you allow to match. If you want to allow 10 non whitspace characters characters not being / or ? then you could use;

(?<=\/ep\/)[^\/?\s]{10}(?=[^\/\s]*$)

Explanation

  • (?<=\/ep\/) Assert /ep/ directly to the left
  • [^\/?\s]{10} Match 10 times any non whitespace character except for / and ?
  • (?=[^\/\s]*$) Assert no more occurrence of / to the right

Regex demo

Or matching 1+ chars other than / ? & instead of exactly 10:

(?<=\/ep\/)[^\/?&\s]+(?=[^\/\s]*$)

Regex demo

Upvotes: 1

Related Questions