Optimizely中使用REGEX匹配URL特定片段失败,寻求解决办法
Hey Charlie, let's break down why your current regex isn't working and get you a solid solution for targeting those template URLs.
What's Wrong With Your Original Regex?
Your regex /(hen)/in-.*/day[^/]+$ has a couple of syntax and logic issues that are throwing off Optimizely's matching:
- Unnecessary regex delimiters: Optimizely expects just the raw regex pattern (no wrapping
/characters) when defining URL rules. That leading/is confusing the matcher. - Misplaced capture group & slash: The
/(hen)/part is incorrectly structured—you don't need to wraphenin parentheses here (unless you're explicitly capturing it, which you didn't mention needing), and the slash after the capture group is out of place. - Incorrect end-of-path matching: The
[^/]+$expects one or more non-slash characters after/day, but your example URL ends cleanly with/day(no extra characters). This is the main reason the match is failing.
Working Regex Solutions
Depending on how flexible your targeting needs to be, here are two tailored options:
1. Exact Match for URLs Starting with /hen/in- and Ending with /day
If all your target URLs follow the pattern https://chillisauce.com/hen/in-*/day (where * is any dynamic text like dublin), use this regex:
^/hen/in-.*/day$
^anchors the match to the start of the URL path (right after the domain)/hen/in-precisely matches that required segment.*safely matches any characters in between (works for dynamic location names)$anchors the match to the end of the URL path, ensuring it closes with/day
2. Match URLs Where /hen/in- Appears Anywhere in the Path (Still Ends with /day)
If the /hen/in- segment could show up later in the path (e.g., https://chillisauce.com/foo/hen/in-dublin/day), use this more flexible version:
.*/hen/in-.*/day$
- The leading
.*allows any characters to appear before the/hen/in-segment
Testing in Optimizely
Paste either regex into Optimizely's URL pattern tester, then input your example URL https://chillisauce.com/hen/in-dublin/day—it should now match successfully. If you need to account for query parameters (e.g., https://chillisauce.com/hen/in-dublin/day?foo=bar), adjust the regex to:
^/hen/in-.*/day(/.*)?$
The (/.*)? makes any trailing path or query parameters optional.
内容的提问来源于stack exchange,提问作者Charlie Howes

