求匹配含"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\bword 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 like249.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:
Or enable it via your regex engine's settings (like using^(?i)(?=.*\bcomp\b)(?=.*\d+(?:\.\d{2})?)\S.*$re.IGNORECASEin Python). - Looser Price Matching: If your prices don't always have two decimal places (e.g.,
250or249.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
\bmarkers 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
相关产品推荐
相关产品推荐

