Regex text between two strings

泄露秘密 提交于 2021-02-05 07:29:24

问题


I am trying to extract data fields from PDF texts using regex.

The text is:

"SAMPLE EXPERIAN CUSTOMER\n2288150 - EXPERIAN SAMPLE REPORTS\nData Dictionary Report\nFiltered By:\nCustom Selection\nMarketing Element:\nPage 1 of 284\n2014-11-11 21:52:01 PM\nExperian and the marks used herein are service marks or registered trademarks of Experian.\n© Experian 2014 All rights reserved. Confidential and proprietary.\n**Data Dictionary**\nDate of Birth is acquired from public and proprietary files. These sources provide, at a minimum, the year of birth; the month is provided where available. Exact date of birth at various levels of detail is available for \n\n\n\n\n\nNOTE: Records coded with DOB are exclusive of Estimated Age (101E)\n**Element Number**\n0100\nDescription\nDate Of Birth / Exact Age\n**Data Dictionary**\n\n\n\n\n\n\n\n\n\n\nFiller, three bytes\n**Element Number**\n0000\n**Description**\nEnhancement Mandatory Append\n**Data Dictionary**\n\n\nWhen there is insufficient data to match a customer's record to our enrichment master for estimated age, a median estimated age based on the ages of all other adult individuals in the same ZIP+4 area is provided. \n\n\n\n\n\n\n00 = Unknown\n**Element Number**\n0101E\n**Description**\nEstimated Age\n"

The field names are in bold. The texts between field names are the field values.

The first time I tried to extract the 'Description' field using the following regex:

pattern = re.compile('\nDescription\n(.*?)\nData Dictionary\n')
re.findall(pattern,text)

The results are correct:

['Date Of Birth / Exact Age', 'Enhancement Mandatory Append']

But using the same idea to extract 'Data Dictionary' Field gives the empty result:

pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n')
re.findall(pattern,text)

Results:

[]

Any idea why?


回答1:


. doesn't match newlines by default. Try:

pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n', flags=re.DOTALL)
re.findall(pattern,text)

Notice how I passed re.DOTALL as the flags argument to re.compile.




回答2:


Try using the flag re.MULTILINE in your regex:

pattern = re.compile('\nData Dictionary\n(.*?)\nElement Number\n', re.MULTILINE)
re.findall(pattern,text)


来源:https://stackoverflow.com/questions/31885340/regex-text-between-two-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!