Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a substring using python if a particular substring occurs in the string?

Tags:

python

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.

like image 445
Lalas M Avatar asked Jul 04 '26 10:07

Lalas M


1 Answers

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)
like image 62
bn_ln Avatar answered Jul 05 '26 23:07

bn_ln