python 从给定字符串中查找子字符串旁边的子字符串

mxg2im7a  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(178)

我如何从给定的字符串中找到与所提到的子字符串相邻的子字符串。
例如:
string ="无法增加索引orcl_index的空间。索引orcl_index的空间应增加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"
6rqinv9w

6rqinv9w1#

如果您愿意使用正则表达式,有一种直接的方法:

import re

inp = "unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb"
val = re.search(r'\bindex (\w+)', inp).group(1)
print(val)  # orcl_index

这里使用的正则表达式模式是\bindex (\w+),表示匹配:

  • \bindex单词“索引”
  • ``单个空格
  • (\w+)匹配下一个字并在第一个捕获组中捕获

相关问题