user13024918
user13024918

Reputation:

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. Example M-LC-123, M-LC-456 and rest all.

How can I achieve this?

Upvotes: 0

Views: 24

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

a simple solution using regular expressions:

pattern = r"(M-LC-(\d+))" means "find every occurence of M-LC- followed by one or more digits"

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:

['M-LC-123', 'M-LC-456', 'M-LC-789', 'M-LC-91011', 'M-LC-121314', 'M-LC-1151617', 'M-LC-181920', 'M-LC-212223']

Upvotes: 1

Related Questions