0

Suppose I have a string "Amar Kulkarni is a Good Boy."

I just want the string between "is an" and "."(a Dot)

I have tried using

    import re
    finalresults = re.search('is an(.+?).', results)
    print(finalresults)

But, it doesn't seems to work out. Help Please.

  • In regexes, the `.` means "any character". If you want a literal `.` character, you need to escape it: `\.`. – gen_Eric Jul 10 '20 at 14:47
  • 1
    Does this answer your question? [How to extract the substring between two markers?](https://stackoverflow.com/questions/4666973/how-to-extract-the-substring-between-two-markers) – Jacques Jul 10 '20 at 14:48
  • In this particular example, _nothing_ is between "is an" and ".". Your string says "is _a_". – ChrisGPT was on strike Jul 11 '20 at 12:13

3 Answers3

0

You have to escape the . using \, Try :

finalresults = re.search('is an(.+?)\.', results)

Note that . is always a wildcard until you escape it.

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
0

This regular expression uses Positive lookbehind and Positive lookahead to match the string.

r'(?<=is an).*?(?=\.)'

Note: this will not match is an and .

https://regex101.com/r/KGiGNQ/1

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0

Try something like:

import re

text = 'a is an b. kk is an c.c.'
try:
     found = re.search('is an(.+?)\.', text).group(1)
except AttributeError:
     found = '' 

print(found)
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Cheolsoon Im
  • 716
  • 1
  • 6
  • 11