0

With this code I can fetch 'John Doe' from 'Name: John Doe'.

But howto fetch when 'John Doe' is on the next line?

Ex:

Name:
John Doe

body = "Name: John Doe"
p = re.compile("Name: (.*)")
   result = p.search(str(body))
   if result:
       s = result.group(1)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • What about this: "Name:( |\n|\r|\r\n)(.*)"? – dan1st May 24 '19 at 08:11
  • 1
    Possible duplicate of [Regular expression matching a multiline block of text](https://stackoverflow.com/questions/587345/regular-expression-matching-a-multiline-block-of-text) – vezunchik May 24 '19 at 08:17

2 Answers2

1

I am not sure entirely what you need, but if you want to find John Doe anywhere in a given input string, then consider using re.findall:

body = "Name: John Doe\nCats don't like bats.\nBut John Doe does."
matches = re.findall(r'\bJohn Doe\b', body)
print(matches)

['John Doe', 'John Doe']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Adding a optional newline char might help. --> \n?\r?

Ex:

import re

body = """Name: John Doe"""

p = re.compile("Name:\s*\n?\r?(.*)")
result = p.search(body)
if result:
    s = result.group(1)
    print(s)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • `\s*` only should work, `\s` is any white character, that includes newlines. ;) So `r"Name:\s*(.*)"` (use r, otherwise Python won't pass a raw string to re.compile and you might need multiple escapes then) – h4z3 May 24 '19 at 08:30