1

How can I find the substring next to a mentioned substring from given string.

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"

indicator substring here is "index", and required output will be "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"
Griffin
  • 65
  • 5
  • I've edited your question to remove the [tag:robotframework] tag because your question doesn't appear related to that tag; what you are asking simply involves string operations in regular python. – Pranav Hosangadi Jan 19 '23 at 04:32
  • Does this answer your question? [How to get the first word in the string](https://stackoverflow.com/questions/13750265/how-to-get-the-first-word-in-the-string) – Pranav Hosangadi Jan 19 '23 at 04:40
  • Are you sure this is the code you are running? There is no `"tablespace"` in your `my_string`. And if you replace that with `"index"` and you get that output for `b`, you are nearly there to getting the output you desire! the question you now need to ask is, "how can I get the first word of a string" ^ – Pranav Hosangadi Jan 19 '23 at 04:41
  • Of course, you have a great answer below showing you how to get it directly using regular expressions should you want to. It is a great tool to have in your arsenal, and there are many great resources on the web, such as https://www.regular-expressions.info/ and https://regex101.com/ – Pranav Hosangadi Jan 19 '23 at 04:45

1 Answers1

3

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 the word "index"
  • single space
  • (\w+) match the next word AND capture in first capture group
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360