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

如何提取特定字符(如#)后直至非数字字符的纯数字子串?

提取特定字符后的纯数字子串解决方案

Hey there! Let's walk through how to solve both of these string extraction scenarios clearly and practically.

场景1:提取#符号之后、首个非数字字符之前的纯数字子串

This is a super common pattern—you want to grab all consecutive digits right after a #, stopping as soon as a non-digit character pops up (or at the end of the string if there's nothing after the digits).

Regular expressions are perfect for this kind of pattern matching. Here's a Python example that does exactly what you need:

import re

def get_num_after_hash(node_name):
    # 正则匹配#后面的连续数字,捕获这个数字组
    match_result = re.search(r'#(\d+)', node_name)
    # 如果匹配到结果,返回捕获的数字;否则返回None
    return match_result.group(1) if match_result else None

# 测试几个典型案例
test_names = [
    "ServerNode#123abc",
    "Database#456",
    "Device#789xyz012",
    "NoHashInName"
]

for name in test_names:
    print(f"Input: {name} → Extracted number: {get_num_after_hash(name)}")

正则说明

  • #:精确匹配#符号
  • (\d+):捕获一个或多个连续的数字(\d代表数字,+表示匹配1次或多次)
  • The regex automatically stops at the first non-digit character after the #, which aligns perfectly with your requirement.

场景2:提取任意特定字符之后仅包含数字的内容

For this generalized case, the approach is similar—we just need to adapt the regex to work with your target character. The key detail here is escaping special regex characters (like ., *, +, ?, etc.) because these have special meanings in regex syntax and would break your match otherwise.

Here's a flexible function that works with any target character:

import re

def get_num_after_target(string, target_char):
    # 转义目标字符,避免正则语法错误
    escaped_char = re.escape(target_char)
    # 构建正则,匹配目标字符后的连续数字
    match_result = re.search(rf'{escaped_char}(\d+)', string)
    return match_result.group(1) if match_result else None

# 测试不同目标字符的情况
test_strings = [
    "Price$999",
    "Version.10",
    "ItemCount+50",
    "NoTargetHere"
]

# 测试$作为目标字符
print("Testing with target character '$':")
for s in test_strings:
    print(f"Input: {s} → Extracted number: {get_num_after_target(s, '$')}")

# 测试.作为目标字符
print("\nTesting with target character '.':")
for s in test_strings:
    print(f"Input: {s} → Extracted number: {get_num_after_target(s, '.')}")

特殊情况处理

If you need to only extract digits that follow the target character and span to the end of the string (i.e., no non-digit characters after the digits), just modify the regex to add $ (end-of-string anchor):

match_result = re.search(rf'{escaped_char}(\d+)$', string)

This way, something like Order#123 will match, but Order#123abc won't—adjust based on your exact needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:21:42