How to store matched part of regex in python?

Question:

The string is

xa0n  xxxxxxnBirchgrove 101,Durga Saffron Square,nKariyammana Agrahara, Bellandur,    [email protected]'

and it is in a list called shipto and it is at index 0 of this list.

the regex I am using is

shipto_re=re.compile(r"\n  xxxxxx\n(.*)(.*?)    xxxxxx")

The part of the string that I want is

Birchgrove 101,Durga Saffron Square,nKariyammana Agrahara, Bellandur,

How do I iterate through the list shipto and store the required regex match in a string variable?

Asked By: Mihir Sanjay

||

Answers:

Your actual text is

 
  xxxxxx
Birchgrove 101,Durga Saffron Square,
Kariyammana Agrahara, Bellandur,    [email protected]

So, the regex you need may look like

n  xxxxxxn(.*n.*)    xxxxxx
n {2}xxxxxxn(.*n.*) {4}xxxxxx

See the regex demo.

See a Python demo below:

import re
shipto=['xa0n  xxxxxxnBirchgrove 101,Durga Saffron Square,nKariyammana Agrahara, Bellandur,    [email protected]']

Here, I printed the variable to see the literal text:

>>> print(shipto[0])
 
  xxxxxx
Birchgrove 101,Durga Saffron Square,
Kariyammana Agrahara, Bellandur,    [email protected]

Next:

match = re.search(r'n {2}xxxxxxn(.*n.*) {4}xxxxxx', shipto[0])
if match:
    print(match.group(1))

Output:

Birchgrove 101,Durga Saffron Square,
Kariyammana Agrahara, Bellandur,
Answered By: Wiktor Stribiżew