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

检查字符串中anchor后至多5字符内是否存在含数字的test子串

解决方案

思路

用正则表达式精准匹配符合要求的子串:先定位anchor,再匹配它之后最多5个任意字符,紧接着匹配test:"+数字(支持整数、小数)+"的结构,同时提取其中的数字内容。

代码实现

import re

s = 'ahlkhsa-anchorawO&B6o77ooiynlhwlkfnbla,)9;}[test:""ajanchorkh,2Yio98vacpoi [p{7}]test:"2"*iuyanchorap07A(p)a test:""*^g8p9JiguanchorLI;ntest:"9.3"'

# 正则匹配anchor后至多5个字符,捕获test:""中的数字
pattern = r'anchor.{0,5}test:"(\d+\.?\d*)"'
matches = re.findall(pattern, s)

if matches:
    print("符合要求的数字内容:")
    for num in matches:
        print(num)
else:
    print("未找到符合条件的子串")

代码说明

  • 正则r'anchor.{0,5}test:"(\d+\.?\d*)"'拆解:
    • anchor:定位锚点字符串
    • .{0,5}:匹配任意0-5个字符,满足"至多5个字符"的距离要求
    • (\d+\.?\d*):捕获数字部分,支持整数(如9)和小数(如9.3),\d+匹配至少1位数字,\.?匹配可选小数点,\d*匹配小数点后可选数字
  • re.findall会返回所有符合条件的数字内容列表

运行结果

执行代码后输出:

9.3

对应示例中符合要求的test:"9.3",其余test子串因距离anchor超过5个字符,不会被匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:50:28