title: Extract text between variable delimiters
body: <p>I have text with large numbers of special characters that I want to extract certain substrings from:</p>
  <pre><code>y &lt;- c(&quot;some stuff &lt;rep&gt; I 1knOw 2LondondErry is bigger than 2LIsburn% &lt;/rep&gt; some stuff &lt;#&gt; &lt;dir&gt; where is Londonderry?&lt;/dir&gt;&quot;,
         &quot;some stuff &lt;rep&gt; &lt;[&gt; But it 's 1nOt an overflow of Belfast% &lt;/rep&gt; &lt;#&gt; potentially more stuff &lt;rep&gt; I 1lIved in Lisburn &lt;/rep&gt;&quot;,
         &quot;&lt;xpa&gt; &lt;[&gt; &lt;unclear&gt; 3 sylls &lt;/unclear&gt; &lt;/[&gt; &lt;/{&gt; &lt;/xpa&gt; blah blub &lt;icu&gt; Yeah &lt;/icu&gt;&quot;)
  </code></pre>
  <p>I want to extract whatever comes between 'tag' like substrings, either <code>&lt;dir&gt; ...&lt;/dir&gt;</code> or <code>&lt;rep&gt; ...&lt;/rep&gt;</code>  or <code>&lt;icu&gt; ...&lt;/icu&gt;</code> and so on:</p>
  <p>With this regex I'm modestly successful:</p>
  <pre><code>library(stringr)
  lapply(y, function(x) paste0(unlist(str_extract_all(x, &quot;&lt;([a-z]{3})&gt;(?!&lt;\\1&gt;).*&lt;/\\1&gt;&quot;)), collapse = &quot;, &quot;))
  [[1]]
  [1] &quot;&lt;rep&gt; I 1knOw 2LondondErry is bigger than 2LIsburn% &lt;/rep&gt;, &lt;dir&gt; where is Londonderry?&lt;/dir&gt;&quot;
  
  [[2]]
  [1] &quot;&lt;rep&gt; &lt;[&gt; But it 's 1nOt an overflow of Belfast% &lt;/rep&gt; &lt;#&gt; potentially more stuff &lt;rep&gt; I 1lIved in Lisburn &lt;/rep&gt;&quot;
  
  [[3]]
  [1] &quot;&lt;xpa&gt; &lt;[&gt; &lt;unclear&gt; 3 sylls &lt;/unclear&gt; &lt;/[&gt; &lt;/{&gt; &lt;/xpa&gt;, &lt;icu&gt; Yeah &lt;/icu&gt;&quot;
  </code></pre>
  <p>Just <code>[[2]]</code>isn't as expected: there is still unwanted material (namely <code>&lt;#&gt; potentially more stuff</code>) and the two occurrences of <code>&lt;rep&gt; ...&lt;/rep&gt;</code> substrings are not separated by <code>,</code>. My hunch is that my regex fails here because the two tags are the same rather than different.</p>
  <p>How can the regex be improved so that this <strong>expected result</strong> is obtained:</p>
  <p><strong>Expected result</strong>:</p>
  <pre><code>[[1]]
  [1] &quot;&lt;rep&gt; I 1knOw 2LondondErry is bigger than 2LIsburn% &lt;/rep&gt;, &lt;dir&gt; where is Londonderry?&lt;/dir&gt;&quot;
  
  [[2]]
  [1] &quot;&lt;rep&gt; &lt;[&gt; But it 's 1nOt an overflow of Belfast% &lt;/rep&gt;, &lt;rep&gt; I 1lIved in Lisburn &lt;/rep&gt;&quot;
  
  [[3]]
  [1] &quot;&lt;xpa&gt; &lt;[&gt; &lt;unclear&gt; 3 sylls &lt;/unclear&gt; &lt;/[&gt; &lt;/{&gt; &lt;/xpa&gt;, &lt;icu&gt; Yeah &lt;/icu&gt;&quot;
  </code></pre>
  <p><strong>EDIT</strong>:</p>
  <p>I've found a viable solution in the meantime:</p>
  <pre><code>lapply(y, function(x) paste0(unlist(str_extract_all(x, &quot;&lt;([a-z]{3})&gt;.*?&lt;/\\1&gt;&quot;)), collapse = &quot;, &quot;))
  </code></pre>