mike
mike

Reputation: 907

re match a pattern

I have some output from a CAS and I want to split up the stuff into three, here is some sample output:

' 1+2;\r\n\r(%o2)                                  3\r\n(%i3) '
'?\r\n\r\n\rpos;\r\n\r(%o1)                                  0\r\n(%i2) '

I'd like to separate the output into three parts:

  1. The part from the beginning of the string to the ';' semi-colon.
  2. The part from after the semi-colon to just before the final \r\n\(%i\d+\)
  3. The final part to be by itself ie.\r\n\(%i\d+\) to always be alone in the final part.

how would I separate them? I'm having trouble creating the code to do that.

EDIT: I'd like the semicolon to be retained even after separating the sections.

Upvotes: 3

Views: 115

Answers (2)

woemler
woemler

Reputation: 7169

This should do what you have requested:

re.findall('^([^;]+);(.*)(\r\n\(%i\d+\).+)$', text, re.S)

To include the semicolon in the first group, just add it to the grouping parenthesis:

re.findall('^([^;]+;)(.*)(\r\n\(%i\d+\).+)$', text, re.S)

Upvotes: 2

NPE
NPE

Reputation: 500683

I am not sure you need regular expressions for this:

In [31]: s = '?\r\n\r\n\rpos;\r\n\r(%o1)                                  0\r\n(%i2) '

In [32]: p1, _, p23 = s.partition(';')

In [33]: p2, _, p3 = p23.rpartition('\r\n')

In [34]: p1, p2, p3
Out[34]: ('?\r\n\r\n\rpos', '\r\n\r(%o1)                                  0', '(%i2) ')

Upvotes: 1

Related Questions