You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求匹配含"comp"与任意价格数字的正则表达式方案

Hey there! Let's work out the regex you need to filter strings that contain both the word "comp" and any price-formatted number.

The Regex You Need

Here's a regex that will do exactly what you want, with explanations broken down below:

^(?=.*\bcomp\b)(?=.*\d+(?:\.\d{2})?)\S.*$

Breakdown of Each Part

Let's break down why this works:

  • ^ & $: Anchor the regex to the start and end of the string, ensuring we check the entire string.
  • (?=.*\bcomp\b): A positive lookahead that guarantees the string contains the standalone word "comp" (the \b word boundaries prevent matching partial words like "competition" or "acomp").
  • (?=.*\d+(?:\.\d{2})?): Another positive lookahead that ensures there's a price-like number:
    • \d+: Matches one or more digits (the whole number part of the price)
    • (?:\.\d{2})?: Optional non-capturing group for a decimal point followed by exactly two digits (matches prices like 249.00; remove the {2} if you want to allow any number of decimal places, or delete the whole group if you only need integers).
  • \S.*: Ensures the string isn't empty (matches at least one non-whitespace character followed by anything else).

Customization Options

  • Case Insensitivity: If you need to match "Comp", "COMP", or other capitalizations, add the case-insensitive flag. You can either include it in the regex:
    ^(?i)(?=.*\bcomp\b)(?=.*\d+(?:\.\d{2})?)\S.*$
    
    Or enable it via your regex engine's settings (like using re.IGNORECASE in Python).
  • Looser Price Matching: If your prices don't always have two decimal places (e.g., 250 or 249.9), adjust the number part to \d+(?:\.\d+)?.
  • No Word Boundaries: If "comp" might be attached to other characters (like "comp-" or "comp123"), remove the \b markers to match any occurrence of the substring "comp".

Example Test Code (Python)

Here's how you can test this regex with your sample strings:

import re

pattern = r'^(?=.*\bcomp\b)(?=.*\d+(?:\.\d{2})?)\S.*$'
test_strings = [
    "249.00 | 259.00 | 279.00 | comp | 349.00 |",
    "comp | 269.00 | 269.00 |",
    "179.00 | 239.00 | comp |",
    "369.00 | 359.00 | 599.00 |"
]

for s in test_strings:
    match = re.match(pattern, s)
    print(f"✅ Matched: {s}" if match else f"❌ Not matched: {s}")

This will correctly match the first three strings and reject the fourth one, just like you need.

内容的提问来源于stack exchange,提问作者Azukah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:45:00