1

The string is formated as '[DATE] record flag: X1.X2.X3.X4.YEAR.NUM;', where DATA is a date string; there is one or two spaces between : and X1; X1, X2, X4 are composed of one or more chars; X3 consisits of zero or more chars; YEAR and NUM are 4 and 3 digits, respectively.

Here is an exmaple: s = '[2011-03-13] record flag: NW.SENSOR..MH1.2011.012;'

How do I cut 'NW' and 'SENSOR' from s?

2 Answers 2

1

Using str.split:

>>> s = '[2011-03-13] record flag: NW.SENSOR..MH1.2011.012;'

>>> s.split(' ')[3].split('.')
['NW', 'SENSOR', '', 'MH1', '2011', '012;']

>>> out = s.split(' ')[3].split('.')

>>> out[0]
'NW'

>>> out[1]
'SENSOR'

Using re.search:

>>> s = '[2011-03-13] record flag: NW.SENSOR..MH1.2011.012;'

>>> out = re.search(r':\s+([^.]+)\.([^.]+)', s)

>>> out.group(1)
'NW'

>>> out.group(2)
'SENSOR'
Sign up to request clarification or add additional context in comments.

2 Comments

peferct, I like the re solution. but btw, why add r before the pattern since without it the expression also gives good results?
@Lee No, r stands for raw. Its there so that the Python takes the string as raw and pass it as it is to Regex without any internal manipulation..
1

Use some splitting and stripping:

parts = s.split(":")[1].strip().split(".")
parts[0] # Should be NW
parts[1] # Should be SENSOR

Comments

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.