简体   繁体   中英

Python regex not capturing groups properly

I have the following regex (?:RE:\w+|Reference:)\s*((Mr|Mrs|Ms|Miss)?\s+([\w-]+)\s(\w+)) .

Input text examples:

  1. RE:11567 Miss Jane Doe 12345678
  2. Reference: Miss Jane Doe 12345678
  3. RE:J123 Miss Jane Doe 12345678
  4. RE:J123 Miss Jane Doe 12345678 Reference: Test Company

Sample Code:

import re

pattern = re.compile('(?:RE:\w+|Reference:)\s*((Mr|Mrs|Ms|Miss)?\s+([\w-]+)\s(\w+))')
result = pattern.findall('RE:11693 Miss Jane Doe 12345678')

For all 4 I expect the output ('Miss Jane Doe', 'Miss', 'Jane', 'Doe') . However in 4th text example I get [('Miss Jane Doe', 'Miss', 'Jane', 'Doe'), (' Test Company', '', 'Test', 'Company')]

How can I get the correct output

Just add ^ to the start of the regex to only match at the start. This makes it ^(?:RE:\w+|Reference:)\s*((Mr|Mrs|Ms|Miss)?\s+([\w-]+)\s(\w+)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM