title: Finding last instance of stringA before StringB in Python
body: <p>I have some strings I am trying to extract from an HTML file. There are many of these strings (long story) and they generally follow the pattern of "Xsomestuffwrittenhere!", with an "X" at the beginning and "!" at the end.</p>
  
  <p>I have written some messy as hell code extracting most of these from the HTML but I'm finding trouble dealing with cases where there is an "!" in the middle of the sections I wish to extract. e.g.</p>
  
  <blockquote>
    <p>XWTF!ThatMakesNoSense!</p>
  </blockquote>
  
  <p>I have been using <em>.find()</em> to get the indexes of the passages to chop them out in the lines of the HTML. e.g.:</p>
  
  <blockquote>
    <p>line[line.find("X"):line.find("!")+1]</p>
  </blockquote>
  
  <p>Within the HTML file (for context: a Facebook messages transcript) everything is formatted all weird (screw you Zuckerberg) and so a X...! can have any sort of text or whatever on either side. I point this out because I have had to add into my code</p>
  
  <blockquote>
    <p>re.search(" ", line[line.find("X"):line.find("!")])</p>
  </blockquote>
  
  <p>to make sure a later "!" doesn't mess with my indexing. e.g.:</p>
  
  <blockquote>
    <p>Xsomething! This is a new sentence!</p>
  </blockquote>
  
  <p>So, the problem I'm having is that I can't work out what to do to distinguish when an "!" is appearing in the middle of a section with an "!" at the end which I want to extract.</p>
  
  <p>I guess the basic problem boils down to: <strong>how can I find the last instance of stringA before the first instance of stringB</strong>, stringB being, in this case, a blank space.</p>
  
  <p>I hope this is all making sense. And sorry for any hopelessness on my part. I haven't programmed in a year since I did this one Python module, and have come back mainly to do this for a project.</p>