Python中匹配第一个点之前字符串的正则表达式方案
Solution to Extract Domain Prefix (Excluding IP Addresses)
Hey there! Let's sort out this regex issue for you.
First, let's break down why your current regex r'(.*)\.(.*)' isn't doing what you want:
- The greedy
.*matches as much as possible, so it actually captures everything up to the last dot (not the first). For example, withyahoo.co.uk, it would grabyahoo.coinstead of justyahoo. - It doesn't distinguish between domain names and IP addresses, so it will happily capture the first octet of an IP like
192from192.168.1.1.
Improved Regex
Here's a regex that captures the part before the first dot only if the input isn't a full IP address:
r'^(?!(?:\d{1,3}\.){3}\d{1,3}$)([^.]+)\.'
Let's break down each component:
^: Anchors the match to the start of the string.(?!(?:\d{1,3}\.){3}\d{1,3}$): Negative lookahead that skips any string formatted as a valid IP address (four dot-separated numeric segments).([^.]+): Captures one or more characters that are not dots—this stops at the first dot, exactly what you want for prefixes likegoogleoryahoo.\.: Matches the first dot (we don't need to capture this, just use it to mark the boundary).
How It Works
- For valid domains like
google.comoryahoo.co.uk, it capturesgoogleandyahoorespectively. - For full IP addresses like
192.168.1.1, the negative lookahead prevents the regex from matching at all, so you won't get unwanted captures like192. - It also works for domains with numeric prefixes (like
123.com), which are valid and should be captured.
Quick Test Cases
| Input | Capture Group 1 |
|---|---|
google.com | google |
yahoo.co.uk | yahoo |
123.net | 123 |
192.168.1.1 | No match |
blog.example.org | blog |
Alternative: If You Want to Avoid Numeric-Only Prefixes
If you don't need to support numeric-only domains (like 123.com) and just want to exclude IP-like segments, you can use this simpler regex to ensure the prefix has at least one letter:
r'^([a-zA-Z0-9-]*[a-zA-Z][a-zA-Z0-9-]*)\.'
Hope this solves your problem!
内容的提问来源于stack exchange,提问作者Jasmin
相关产品推荐
相关产品推荐

