I'm trying to return or print a specific substring that occurs before a search keyword in a very lengthy string using python.
For example if my string is as below
string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"
If the search keyword is apple then 0 (which is the id) should be printed
if the search keyword is orange that 1 (which are the ids) should be printed
if the search keyword is fox then 3 and 4 (which is the id) should be printed
I'm expecting the id of the keyword as given in the example. In my case all the searchable keywords are associated with an id as in the example string.
You can use the following regex to return the indices and key word matches.
import re
def find_id(string, word):
pattern = r'id[:=](\d+),[\w\s]+' + word
return list(map(int, re.findall(pattern, string)))
string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"
print(find_id(string, 'fox'))
Output:
[3, 4]
I have returned ints but if this isn't necessary then you can return the indices as strings ['3', '4'] by replacing the return line with;
return re.findall(pattern, string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With