[英]Extract string starting with specific string in a string in Python
I have data as follows我有如下数据
[{"ruleId":"RULE","ruleName":"Dependency_rule","ruleDescription":"package rules ; import ava; rule \"M-LC-123 Dependency\" when accountO:Account ( !(Ids contains \"M-LC-456\") && !(Ids contains \"M-LC-789\") && !(Ids contains \"M-LC-91011\") && !(Ids contains \"M-LC-121314\") && !(Ids contains \"M-LC-1151617\") && !(Ids contains \"M-LC-181920\") && !(Ids contains \"M-LC-212223\")) then accO.setBlock(false); end ","ruleType":"DEPEND","ruleExpression":null}]
I want to extract all the values which start with M-LC from this.我想从中提取所有以 M-LC 开头的值。 Example M-LC-123, M-LC-456 and rest all.示例 M-LC-123、M-LC-456 和 rest 全部。
How can I achieve this?我怎样才能做到这一点?
a simple solution using regular expressions :使用正则表达式的简单解决方案:
pattern = r"(M-LC-(\d+))"
means "find every occurence of M-LC-
followed by one or more digits" pattern = r"(M-LC-(\d+))"
意思是“找到每一个出现的M-LC-
后跟一个或多个数字”
import re
data = [{"ruleId":"RULE","ruleName":"Dependency_rule","ruleDescription":"package rules ; import ava; rule \"M-LC-123 Dependency\" when accountO:Account ( !(Ids contains \"M-LC-456\") && !(Ids contains \"M-LC-789\") && !(Ids contains \"M-LC-91011\") && !(Ids contains \"M-LC-121314\") && !(Ids contains \"M-LC-1151617\") && !(Ids contains \"M-LC-181920\") && !(Ids contains \"M-LC-212223\")) then accO.setBlock(false); end ","ruleType":"DEPEND","ruleExpression":None}]
data_str = str(data) # prevents need to iterate list/dicts
pattern = r"(M-LC-(\d+))"
results = [m.group(0) for m in re.finditer(pattern, data_str)]
print(results)
Output: Output:
['M-LC-123', 'M-LC-456', 'M-LC-789', 'M-LC-91011', 'M-LC-121314', 'M-LC-1151617', 'M-LC-181920', 'M-LC-212223']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.