undefinedfix
Sign in

Python regexp reverse matching

Nahuel edited in Fri, 23 Sep 2022

There is such a string, is a SMS template as follows: Dear Zhang San, your current consumption is 1 yuan, the balance is 0 yuan, if you have any questions, please contact customer service 400-800-8888. I need to get several fields like Zhang San 10 through regular expression, but the values of name, consumption and balance change. How can I use other unchanging fields to get the three changed fields? Thank you!

>>>import re

>>>str1 = '亲爱的张三,您的本次消费1元,余额为0元,如有疑问,请联系客服400-800-8888。'
>>>re.findall(r'这里要怎么写',str1)
>>>['张三',0,1]
2 Replies
ichster
commented on Fri, 23 Sep 2022

Since the text is so regular, it is easy to write as follows:

import re

str1 = '亲爱的张三,您的本次消费1元,余额为0元,如有疑问,请联系客服400-800-8888。'
print(re.findall(r'亲爱的(.*?),.*?消费(.*?)元.*?余额为(.*?)元',str1))

[('张三', '1', '0')]
Sofia
commented on Fri, 23 Sep 2022
import re
str = "亲爱的张三,您的本次消费1元,余额为0元,如有疑问,请联系客服400-800-8888。"
result=re.findall(r"(?<=亲爱的)[^,]+|[\d.]+(?=元)",str)
print(result)