74

I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:

String = "This is an example sentence, it is for demonstration only"
re.search("is", String)

I'd like to know the position(s) of where the 'is' matches are found so that I can extract and output something like this:

1 match found: "This is an example sentence"

I know that it would be easy to do with splits, but I'd need to know what the index of first character of the match was in the string, which I don't know how to find

1
  • 6
    you'd actually find "is" twice in your example.
    – extraneon
    Apr 20, 2010 at 10:51

3 Answers 3

102

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

4
  • No idea how I missed this in the documentation, does exactly what I needed it to, thanks!
    – nb.
    Apr 20, 2010 at 10:57
  • If you want to grab only word "is" I think re.search(" is ", String).start() should word also .. of course there are other examples too.
    – kuskmen
    Nov 4, 2015 at 20:57
  • 1
    Be wary of the fact that re.search returns None if there is no match. Jan 5, 2017 at 14:09
  • 1
    How would I search for a list instead of a single word ? like [0-9]? Jan 20, 2021 at 11:47
77

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

1
  • 1
    Yes, thank you for this. I was looking for this. OP asked for position(s) but accepted answer only returns 1 position.
    – Swedgin
    Nov 7, 2019 at 10:11
38

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.