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

获取Nginx配置中whitelist大括号内内容的正则表达式需求

Extract Content from Nginx's geo $whitelist Block

Let's fix your regex issue and pull the content inside the curly braces of the geo $whitelist block properly.

First, let's break down why your original regex didn't work:

  • re.match() only checks for matches starting at the beginning of the string, which isn't ideal here (even if your sample is standalone, the pattern doesn't target the specific geo $whitelist prefix).
  • The pattern \{(\s*?.*?)*?\} is too vague—it could match any curly braces in the text, not just the ones tied to your target block.

Working Solution

Here's a targeted regex and Python code to extract exactly the content inside the geo $whitelist block's curly braces:

import re

# Your sample nginx config content
conf_text = "geo $whitelist { default 1; 1.1.1.1/32 0; 2.1.1.1/32 0; 3.3.3.3/32 0; }"

# Regex pattern tailored to the geo $whitelist block
# - `geo \$whitelist`: Matches the exact block start (escaping $ since it's a regex special character)
# - `\s*\{\s*`: Matches the opening curly brace with any surrounding whitespace (handles line breaks/spaces)
# - `(.*?)`: Non-greedy capture of all content inside the braces
# - `\s*\}`: Matches the closing curly brace with any surrounding whitespace
# - `re.DOTALL`: Makes `.` match newlines (works for multi-line configs too)
match = re.search(r'geo \$whitelist\s*\{\s*(.*?)\s*\}', conf_text, re.DOTALL)

if match:
    # Get the content inside the braces
    inner_content = match.group(1)
    print("Content inside the block:\n", inner_content)

Output

Content inside the block:
 default 1; 1.1.1.1/32 0; 2.1.1.1/32 0; 3.3.3.3/32 0

Bonus: Extract Just the IP Whitelist Entries

If you want to go a step further and pull out only the IP/CIDR entries (excluding the default rule), you can process the captured content:

if match:
    inner_content = match.group(1)
    # Split rules by semicolon, strip whitespace, and filter out empty strings
    rules = [rule.strip() for rule in inner_content.split(';') if rule.strip()]
    # Extract only the IP/CIDR parts from non-default rules
    ip_entries = [rule.split()[0] for rule in rules if not rule.startswith('default')]
    print("Whitelisted IPs:\n", ip_entries)

Output

Whitelisted IPs:
 ['1.1.1.1/32', '2.1.1.1/32', '3.3.3.3/32']

This approach works for both single-line and multi-line geo blocks, which is common in real-world Nginx configurations.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:11:44