Search code examples
pythonregexfindall

Trying to search for a string with (.*?) in Python


I am 3 days new to Python and I am trying to use findall() to search for a string character after a specified format

    >>> nameRegex = re.compile(r'First Name: (.*?) Last Name: (.*?)')
    >>> nameRegex.findall('This is my application for the job. First Name: 
       John Last Name: Johnson DOB 01/01/90')
    >>> [('John', '')]

I realize I am using the non greedy ? in the group because otherwise it would return the DOB portion of the string as well.

Is there a way I could format to take the Johnson string portion and nothing more?

Since I am so new I am not sure which direction to move to get the desired portion of the string.

Thanks to anyone in advance.


Solution

  • Anchor your regex pattern with a space in the end. That should help you to capture everything after Last Name: upto the next space

    >>> nameRegex = re.compile(r'First Name: (.*?) Last Name: (.*?) ')
    >>> nameRegex.findall('This is my application for the job. First Name: John Last Name: Johnson DOB 01/01/90')
    [('John', 'Johnson')]