We’re using a proprietary tracking system that requires the use of regular expressions to load third party scripts on the URLs we specify.
I wanted to check the syntax of the regex we’re using to see if it looks right.
To match the following URL
/products/18/indoor-posters
We are using this rule:
.*\/products\/18\/indoor-posters.*
Does this look right? Also, if there was a query parameter on the URL, would it still work? e.g.
/products/18/indoor-posters?someParam=someValue
There’s another URL to match:
/products
The rule for this is:
.*\/products
Would this match correctly?
Well, “right” is a relative term. Usually,
.*is not a good idea because it matches anything, even nothing. So while these regexes will all match your example strings, they’ll also match much more. The question is: What are you using the regexes for?If you only want to check whether those substrings are present anywhere in the string, then they are fine (but then you don’t need regex anyway, just check for substrings).
If you want to somehow check whether it’s a valid URL, then no, the regexes are not fine because they’d also match
foo-bar!$%(§$§$/products/18/indoor-postersssssss)(/$%/§($/.If you can be sure that you’ll always get a correct URL as your input and just want to check whether they match you pattern, then I’d suggest
to match any URL that ends in
/products, andto match a URL that ends in
/products/18/indoor-posterswith an optional?name=valuebit at the end, assuming only alphanumeric characters are legal fornameandvalue.