Home > Blockchain >  How to store matched part of regex in python?
How to store matched part of regex in python?

Time:07-21

The string is

\xa0\n  xxxxxx\nBirchgrove 101,Durga Saffron Square,\nKariyammana Agrahara, Bellandur,    [email protected]\n'

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?

CodePudding user response:

Your actual text is

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

So, the regex you need may look like

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

See the regex demo.

See a Python demo below:

import re
shipto=['\xa0\n  xxxxxx\nBirchgrove 101,Durga Saffron Square,\nKariyammana Agrahara, Bellandur,    [email protected]\n']

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}xxxxxx\n(.*\n.*) {4}xxxxxx', shipto[0])
if match:
    print(match.group(1))

Output:

Birchgrove 101,Durga Saffron Square,
Kariyammana Agrahara, Bellandur,
  • Related