Lil Jo
Lil Jo

Reputation: 21

Match string between two characters

I'm looking for a regex command which gives me from a string the word which is between the last "/" and "&".

String:

://name.prod.something-blabla.com/erp/apps/appname/appname.text#/com/text/prod/appname/uil/partner/PartnerBearbeiten&unternehmenId1=Z0004dw

Desired output: PartnerBearbeiten

I tried: ([^\/]+\&) but it includes the & (PartnerBearbeiten&)

Image: Regex code in a xml

Upvotes: 0

Views: 87

Answers (4)

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

Using a lookahead as shown in other answers is certainly possible here but I’d argue that the canonical solution to the problem of matching a substring between two delimiting characters is to exclude the last character from the match character class:

/([^/&]+)&

This has the advantage of making the overall expression simpler, and working efficiently without using non-greedy matching: using a lookahead assertion without non-greedy matching would force the regular expression to backtrack, which can be inefficient in this case (using non-greedy +? instead of + would also solve this, though).

Lookahead assertions are best reserved for cases that cannot be expressed differently. In this particular case, they are simply redundant.

Upvotes: 0

Shariq
Shariq

Reputation: 506

Try this:

([^\/])*(?=&) <br>

Tested with Javascript.

Upvotes: 0

Andreas
Andreas

Reputation: 2521

You could use regex lookahead to exclude any matches from the result. So, to exclude & in that particular pattern, the regex would be ([^/]+(?=\&)) (check on this RegExr website)

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You can use a positive lookahead:

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

See demo.

Note that I made character class lazy (using +?), in order to work with multi-parameters URL.

Upvotes: 2

Related Questions