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

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, with yahoo.co.uk, it would grab yahoo.co instead of just yahoo.
  • It doesn't distinguish between domain names and IP addresses, so it will happily capture the first octet of an IP like 192 from 192.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 like google or yahoo.
  • \. : 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.com or yahoo.co.uk, it captures google and yahoo respectively.
  • 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 like 192.
  • It also works for domains with numeric prefixes (like 123.com), which are valid and should be captured.

Quick Test Cases

InputCapture Group 1
google.comgoogle
yahoo.co.ukyahoo
123.net123
192.168.1.1No match
blog.example.orgblog

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:13:19