简体   繁体   English

从给定的字符串中找到 substring 旁边的 substring

[英]Find a substring next to a substring from a given string

How can I find the substring next to a mentioned substring from given string.如何从给定字符串中找到提到的 substring 旁边的 substring。

For example:例如:

string = "unable to increase the space of the index orcl_index. The space for the index orcl_index should be increased by 250mb" string = "无法增加索引orcl_index的空间。索引orcl_index的空间应该增加250mb"

indicator substring here is "index", and required output will be "orcl_index".指标 substring 这里是“索引”,所需的 output 将是“orcl_index”。

I tried the following the code, but not sure how to proceed further我尝试了以下代码,但不确定如何继续

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"

If you're open to using regular expressions, there is a straightforward way:如果您愿意使用正则表达式,则有一种直接的方法:

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

The regex pattern used here is \bindex (\w+) , which says to match:这里使用的正则表达式模式是\bindex (\w+) ,表示匹配:

  • \bindex the word "index" \bindex单词“索引”
  • single space单空间
  • (\w+) match the next word AND capture in first capture group (\w+)匹配下一个词并在第一个捕获组中捕获

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM