NSF
NSF

Reputation: 2549

How to get the certain segment of a URL using regex?

Say the url is http://aa/bb/cc. "aa" is in segment 1, "bb" in 2 and "cc" in 3. How could the regex extract the given number of segment? (so it would be something like \2, \3 which refers to that part of URL.)

Upvotes: 0

Views: 2162

Answers (2)

Ria
Ria

Reputation: 10347

Try this regex:

http:/(?:/([^/]+))+

explaination:

(subexpression) Captures the matched subexpression and assigns it a zero-based ordinal number.

(?:subexpression) Defines a noncapturing group.

+ Matches the previous element one or more times.

[^character_group] Negation: Matches any single character that is not in character_group.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425033

Try this:

http://(.*?)/(.*?)/(.*?)

The regex .*? is a "non-greedy" match.

Upvotes: 0

Related Questions