0

Hi I am writing a script that requires some regex pattern matching but I am unable to make matches.

here is a MCVE:

import re

sourceString= 'Hi I want pizza for lunch'

patternObject=re.compile('pi.*');
match=patternObject.match(sourceString);

if match:
     print("the match is:",match.group())
else:
     print("no matches found!");

Unfortunately output of the program is "no matches found!" despite "pizza for lunch" being the desired output. What did I understand wrong?

ForeverStudent
  • 2,487
  • 1
  • 14
  • 33
  • 2
    You missed the dot before *: `'pi.*'` And use re.search as `pi` is not at the start of the string. – Wiktor Stribiżew Mar 02 '16 at 17:43
  • @WiktorStribiżew correct, I have edited my question to include the dot before the asterisk,however I still get the same result (no matches). on a sidenote, even missing the dot should give me the substring "pi" not a no match. what is re.search? should I use it in place of re.compile? how does this impact "pi" not being at the beginning of the string? – ForeverStudent Mar 02 '16 at 18:54
  • `re.search` looks for a match anywhere inside a string, `re.match` only looks for a match at the string start. – Wiktor Stribiżew Mar 02 '16 at 19:11
  • OK thanks that helped, but it seems like re.search only searches the first line and ignores all lines that happen after newline \n. is there a way for me to search a big source string that has a newline in it? ( I wanna search all lines, not one by one) – ForeverStudent Mar 02 '16 at 19:37
  • Use `re.DOTALL` modifier: `patternObject=re.compile('pi.*', re.DOTALL);` – Wiktor Stribiżew Mar 02 '16 at 19:45
  • Thanks, dotall didnt work but multiline did – ForeverStudent Mar 02 '16 at 20:04

0 Answers0