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

如何用Python正则表达式在无空格连续字符串中查找数字/IP/整数?

Solution to Extract Numeric Sequences and IP-like Strings

First, let's break down why your initial loop approach didn't work:

  • You're iterating over individual characters, so you can only capture single digits instead of continuous sequences like 123 or 1.2.3.4.
  • The check if a in range(9) is invalid: range(9) produces integers 0-8, but a is a string character (like '9'), so they can't be compared directly. Even if you used a.isdigit(), you'd still only get isolated digits, not the grouped sequences you need.

Working Regex Approach

Regular expressions are perfect here because they can match patterns of continuous digits and optional dot-separated number segments. Here's the code that will extract exactly what you need:

import re

# Your input text
input_text = "randomblahblah123iwanttosearchthis666number1.2.3.4withpython"

# Regex pattern to match:
# - \b: Word boundary (ensures we don't capture partial sequences attached to letters)
# - \d+: One or more digits
# - (?:\.\d+)*: Non-capturing group for zero or more ".digit" segments (handles IP-like strings)
pattern = r'\b\d+(?:\.\d+)*\b'

# Extract all matches
matches = re.findall(pattern, input_text)

# Format the output as requested
print(', '.join(matches))  # Output: 123, 666, 1.2.3.4

How the Regex Works

Let's break down the pattern piece by piece:

  • \b: Acts as a marker between alphanumeric characters and non-alphanumeric characters (or start/end of string). This ensures we don't accidentally capture something like blah123 as part of a longer word—we only get the standalone numeric sequences.
  • \d+: Matches one or more consecutive digits (covers 123 and 666).
  • (?:\.\d+)*: The (?:...) is a non-capturing group (we don't need to extract the individual dot segments separately), and \.\d+ matches a dot followed by one or more digits. The * means this can repeat zero or more times—so it handles both plain numbers (zero repeats) and IP-like strings (three repeats, like 1.2.3.4).

Optional: Strict IP Validation

If you ever need to ensure the dot-separated sequence is a valid IP address (each segment 0-255), you can use a more precise pattern:

strict_ip_pattern = r'\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
strict_matches = re.findall(strict_ip_pattern, input_text)

But for your current use case, the simpler pattern is sufficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:30:17