如何在python中使用正则表达式来提取触摸逗号的文本?

例如

Str= "Select Name,Email,Contact (Select Subject,ActivityDate,Description from Opportunity) from Opportunity"

Desired_List = ['Name','Email','Contact','Subject','ActivityDate','Description']

这是另一个要测试的字符串:

Str = "Select Invoice_Number__c,ID,Name,Owner.Name,Amount,Billing_Email__c,Payment_Terms__c,Invoice_Schedule__c,Opt_Out_Date__c,CloseDate,Contract_Start_Date__c,Contract_End_Date__c,(Select Subject,ActivityDate,           Description from ActivityHistories ORDER By ActivityDate DESC NULLS LAST)from Opportunity where StageName = 'Closed Won' ANDType != 'Upsell' ANDInvoice_Number__c != '' LIMIT 2"

请注意,逗号和说明之间有很大的空间。

===============>>#1 票数:6 已采纳

使用正向先行和向后搜索来匹配在逗号两侧的单词。

import re

Str= "Select Name,Email,Contact (Select Subject,ActivityDate,Description from Opportunity) from Opportunity"

matches = re.findall(r"\w+(?=,)|(?<=,)\w+", Str)
print matches

输出:

['Name', 'Email', 'Contact', 'Subject', 'ActivityDate', 'Description']

这些都记录在这里

更新:使用OP的新字符串:

['Invoice_Number__c', 'ID', 'Name', 'Owner', 'Name', 'Amount', 'Billing_Email__c', 'Payment_Terms__c', 'Invoice_Schedule__c', 'Opt_Out_Date__c', 'CloseDate', 'Contract_Start_Date__c', 'Contract_End_Date__c', 'Subject', 'ActivityDate', 'Description']

  ask by Chris translate from so

未解决问题?本站智能推荐: