Skip to content
Fix Code Error

How to extract the substring between two markers?

March 13, 2021 by Code Error
Posted By: Anonymous

Let’s say I have a string 'gfgfdAAA1234ZZZuijjk' and I want to extract just the '1234' part.

I only know what will be the few characters directly before AAA, and after ZZZ the part I am interested in 1234.

With sed it is possible to do something like this with a string:

echo "$STRING" | sed -e "s|.*AAA(.*)ZZZ.*|1|"

And this will give me 1234 as a result.

How to do the same thing in Python?

Solution

Using regular expressions – documentation for further reference

import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

or:

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234
Answered By: Anonymous

Related Articles

  • Clearing a polyline on a Polymer Google Map
  • What are the undocumented features and limitations of the…
  • Reference - What does this regex mean?
  • Can't install via pip because of egg_info error
  • Form field border-radius is not working only on the last…
  • Pass array and/or object data between Polymer elements
  • GLYPHICONS - bootstrap icon font hex value
  • Alternative to header("Content-type: text/xml");
  • What's the difference between eval, exec, and compile?
  • Any quick way of updating a column based on timestamp

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)

Next Post:

Get the client IP address using PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error