Home > Net >  RegEx URL Minor Patten Match Issue regarding '?'
RegEx URL Minor Patten Match Issue regarding '?'

Time:08-27

All,

Been struggling to not-match a single use case regarding a query (?). See below tests matches/non-matches. I dont want to match if the ? is following the first / after hostname segment, but do want match if ? follows any other path trailing /. Regarding language, a JS variant that doesn't require the escapes (\).

^/(solutions|solucoes|soluciones|oplossingen|losungen)/. ($|\?|\/($|\?))

Matches:

/solutions/test
/solutions/test/
/solutions/test?param
/solutions/test/?param

/solutions/test/testb
/solutions/test/testb/
/solutions/test/testb/?param
/solutions/test/testb?param

/solutions/?param (match - My problem child, dont want a match here)

Non-Matches

/solutions
/solutions/
/solutions?

CodePudding user response:

You're close here. After your second slash you need to add a negative lookahead for a question mark. Negative lookaheads are successful if they do not match what follows, but they also do not move the scan cursor forward, so the characters will be rescanned a second time.

The negative lookahead is (?!\?). Then I simplified your following code to . $ because if you have the /m flag set, $ will match end of line. Make sure the multi-line flag (/m) is set.

^\/(solutions|solucoes|soluciones|oplossingen|losungen)\/(?!\?). $

Here's a screen print of it enter image description here

CodePudding user response:

You might exclude matching a question mark after the forward slash by matching a single character other than a newline or question mark using a negated character class.

^\/(solutions|solucoes|soluciones|oplossingen|losungen)\/[^\r\n?].*$

Regex demo

  • Related