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

如何从给定字符串中查找指定子串紧邻的目标子串

查找指定子串紧邻的后续子串问题解决

问题描述

给定字符串:

"unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb"

需要找到标识子串index紧邻的后续子串,期望输出为orcl_index。

用户尝试了以下代码,但输出不符合预期:

my_string = "unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb"

print(my_string.split("index",1)[1])

a= my_string.split("index",1)[1]

b= a.strip()
print(b)

# Output: " orcl_index should be increased by 250mb"
# Required output: "orcl_index"

解决方案

方法1:基于split的后续处理

在现有代码基础上,对处理后的字符串再次分割,取第一个元素即可:

my_string = "unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb"

a = my_string.split("index", 1)[1]
b = a.strip()
# 按空格分割后取第一个元素
result = b.split()[0]
print(result)  # 输出: orcl_index

方法2:使用正则表达式(更通用)

如果需要匹配所有符合条件的子串,或者目标子串格式有规律,用正则表达式更灵活:

import re

my_string = "unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb"

# 匹配index后紧邻的非空格/非标点内容
pattern = r'index\s+([^\s.]+)'
matches = re.findall(pattern, my_string)

print(matches)  # 输出: ['orcl_index', 'orcl_index']
# 取第一个匹配项
print(matches[0])  # 输出: orcl_index

如果目标子串是固定格式的标识符(如下划线连接),也可以用更精准的正则:r'index\s+(\w+_\w+)'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:11:13