L457
L457

Reputation: 1032

Regex: find word between slash and matching keyword in url

eg:

http://www.domain.com/junk/target/keyword/junk

I'm trying to pull the word 'target' from the above url. So far I have the following expression:

(?=\/).*?(?=\/keyword\/)

however this pulls everything from the first slash ('//www.domain.com/junk/target')

Upvotes: 2

Views: 971

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

%r{/([^/]+)/keyword/}

See the Rubular demo (note that if keyword may appear at the end of the string, you will need to add an alternation at the end - %r{/([^/]+)/keyword(?:/|\z)}).

The value you need is inside Group 1.

Ruby demo:

lnk[%r{/([^/]+)/keyword/}, 1]

Pattern description:

  • / - a slash
  • ([^/]+) - Capturing group 1 matching one or more chars other than /
  • /keyword/ - a literal /keyword/ substring.

Upvotes: 3

Josh Crozier
Josh Crozier

Reputation: 241278

You can use a negated character class in combination with the positive lookahead:

[^\/]+(?=\/keyword)

Explanation:

  • [^\/]+ - Negated character set to match one or more / characters
  • (?=\/keyword) - Positive lookahead to match the following /keyword string.

Of course you could also just use a capturing group:

\/([^\/]+)\/keyword

The string target would be in the first group.

Upvotes: 2

Related Questions