寻求匹配URL中‘events’与‘go-’的最优正则表达式用于A/B测试
Hey Charlie, let’s nail this regex for your A/B testing targeting—super common use case, so I’ll cover a couple of scenarios depending on your URL structure.
核心需求回顾
You need to match URLs that include both:
- The business unit segment:
events - The product page template prefix:
go-
场景1: 匹配同时包含两者的URL(无顺序要求)
If you just need to validate that a URL has both events and go- (regardless of their order in the path), this regex works:
^https?://.*(events).*(go-)|.*(go-).*(events).*$
解释:
^https?://: 匹配HTTP/HTTPS URL的开头(如果只匹配路径字符串,可以去掉这部分).*(events).*(go-): 匹配events出现在go-之前的URL|: 逻辑或运算符,覆盖两种顺序情况.*(go-).*(events).*: 匹配go-出现在events之前的URL$: 确保匹配完整URL(可选,取决于你的工具要求)
场景2: 更精准的路径匹配(常见结构)
如果你的URL有固定结构——比如events是顶层或嵌套路径段,go-作为产品页面名称的前缀(例如https://your-site.com/events/go-summer-workshop或https://your-site.com/products/go-premium-plan/events/registration),可以用更严格的正则:
^https?://.*\/events\/.*\/go-[^\/]+|.*\/go-[^\/]+.*\/events\/.*$
解释:
\/events\/: 确保events是完整的路径段(避免匹配eventsite这类包含events的字符串)\/go-[^\/]+: 匹配以go-开头的路径段([^\/]+会捕获产品名称直到下一个斜杠)- 逻辑或运算符覆盖
events和go-路径段的两种顺序
提取特定部分(如果需要)
如果你需要提取events段或完整的go-产品路径,可以添加捕获组。比如要抓取go-开头的产品段:
^https?://.*(events).*\/(go-[^\/]+)|.*\/(go-[^\/]+).*(events).*$
你的A/B测试工具(比如Optimizely、Google Optimize等)会允许你通过编号引用这些捕获组(例如根据顺序使用$2或$3)。
注意事项
- 一定要用你实际的URL示例测试!正则的有效性高度依赖具体的URL结构,可以用在线工具验证并调整。
- 如果你的测试工具允许部分匹配(不需要完整URL),可以简化为
events.*go-|go-.*events直接匹配路径。
Hope this gets you set up perfectly for your tests!
内容的提问来源于stack exchange,提问作者Charlie Howes

