简体   繁体   English

正则表达式可在Python中找到两个字符串之间的字符串

[英]Regex expression to find strings between two strings in Python

I am trying to write a regular expression which returns a string which is between two other strings. 我正在尝试编写一个正则表达式,该表达式返回一个位于其他两个字符串之间的字符串。 For example: I want to get the string along with spaces which resides between the strings "15/08/2017" and "$610,000" 例如:我想获取字符串以及位于字符串“ 15/08/2017”和“ $ 610,000”之间的空格

a='172 211 342    15/08/2017  TRANSFER OF LAND   $610,000        CASH & MTGE'

should return 应该回来

"TRANSFER OF LAND"

Here is the expression I have pieced together so far: 到目前为止,这是我拼凑的表达方式:

re.search(r'15/08/2017(.*?)$610,000', a).group(1)

It doesn't return any matches. 它不返回任何匹配项。 I think it is because we also need to consider spaces in the expression. 我认为是因为我们还需要考虑表达式中的空格。 Is there a way to find strings between two strings ignoring the spaces? 有没有办法找到两个字符串之间的字符串而忽略空格?

Use Regex Lookbehind & Lookahead 使用正则表达式Lookbehind & Lookahead

Ex: 例如:

import re

a='172 211 342 15/08/2017 TRANSFER OF LAND $610,000 CASH & MTGE'
print(re.search(r"(?<=15/08/2017).*?(?=\$610,000)", a).group())

Output: 输出:

 TRANSFER OF LAND 
>>> re.search(r'15/08/2017(.*)\$610,000',a).group(1)
'  TRANSFER OF LAND   '

Since $ is a regex metacharacter (standing for the end of a logical line), you need to escape it to use as a literal '$' . 由于$是正则表达式元字符(代表逻辑行的结尾),因此您需要对其进行转义以用作文字'$'

Might be easier to use find : 可能更容易使用find

a = '172 211 342 15/08/2017 TRANSFER OF LAND $610,000 CASH & MTGE'
b = '15/08/2017'
c = '$610,000'

a[a.find(b) + len(b):a.find(c)].strip()

'TRANSFER OF LAND' “土地转让”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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