Chr*_*ris 2 python regex string
如何在python中使用正则表达式来拉动接触逗号的文本?
例如
Str= "Select Name,Email,Contact (Select Subject,ActivityDate,Description from Opportunity) from Opportunity"
Desired_List = ['Name','Email','Contact','Subject','ActivityDate','Description']
Run Code Online (Sandbox Code Playgroud)
这是另一个要测试的字符串:
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"
Run Code Online (Sandbox Code Playgroud)
请注意,逗号和描述之间有一个很大的空格.
使用正向前瞻和后视来匹配两边逗号边界的单词.
import re
Str= "Select Name,Email,Contact (Select Subject,ActivityDate,Description from Opportunity) from Opportunity"
matches = re.findall(r"\w+(?=,)|(?<=,)\w+", Str)
print matches
Run Code Online (Sandbox Code Playgroud)
输出:
['Name', 'Email', 'Contact', 'Subject', 'ActivityDate', 'Description']
Run Code Online (Sandbox Code Playgroud)
这些都记录在这里.
更新:使用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']
Run Code Online (Sandbox Code Playgroud)