0

I have a character list in this format "EXECUTE SYS-SM-THIS-1004"

What's the efficient way to split this list based on the conditions:

  1. From the list, consider the characters after EXECUTE, split them using hyphen(-) as delimiter
  2. From the resulting list, first element must be equal to any one of [SYS, CSC, ISC]
  3. Last word must be a 4 digit number
  4. Contents between first and last words to be moved into a new list after removing the Leading and ending hyphens. Finally hyphen to be replaced with underscore.

Condition to find if the line has the work EXECUTE is working. How to check the other conditions?

if re.match('^\s*EXECUTE .*', line) or re.match('^\s*execute.*', line) :

Input:

a = ["EXECUTE SYS-SM-THIS-1004"]

Expected Output:

X = SYS
Y = SM_THIS
Z = SYS-SM-THIS-1004
2
  • that's just checking for both the cases. edited now Commented Jun 6, 2019 at 10:43
  • You can use the re.I or IGNORECASE flag fot that. Commented Jun 6, 2019 at 10:46

1 Answer 1

2

Using re.match

Ex:

import re
s = "EXECUTE SYS-SM-THIS-1004"
m = re.match(r"EXECUTE (?P<Z>(?P<X>SYS|CSC|ISC)\-(?P<Y>\S+)\-\d{4})$", s.strip())
if m:
    X = m.group("X")
    Y = m.group("Y").replace("-", "_")
    Z = m.group("Z")
    print(X, Y, Z)

Output:

('SYS', 'SM_THIS', 'SYS-SM-THIS-1004')
Sign up to request clarification or add additional context in comments.

6 Comments

This does not replace - with _ in Y, but doing this after the regex match would be trivial. But maybe use \S+ instead of .*??
Sorry did not see that info in the que.
If the match fails for "SYS|CSC|ISC", how do the error get captured
@Osceria. If it does not match it will not come inside the if condition if m
@Rakesh I'm just trying to understand how exactly does this regex work. Can you help me with that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.