Finding and extracting multiple substrings in a string?
<p>After looking <a href="http://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="http://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="http://stackoverflow.com/questions/6633678/finding-words-after-keyword-in-python">similar</a> <a href="http://stackoverflow.com/questions/11472442/grab-first-word-in-string-after-id">questions</a>, I have not been able to successfully implement a substring split on my data. For my specific case, I have a bunch of strings, and each string has a substring I need to extract. The strings are grouped together in a list and my data is NBA positions. I need to pull out the positions (either 'PG', 'SG', 'SF', 'PF', or 'C') from each string. Some strings will have more than one position. Here is the data.</p>

<pre><code>text = ['Chi\xa0SG, SF\xa0\xa0DTD','Cle\xa0PF']
</code></pre>

<p>The code should ideally look at the first string, <code>'Chi\xa0SG, SF\xa0\xa0DTD'</code>, and return <code>['SG','SF']</code> the two positions. The code should look at the second string and return <code>['PF']</code>.</p>

<p>Leverage (zero width) lookarounds:</p>

<pre><code>(?&lt;!\w)PG|SG|SF|PF|C(?!\w)
</code></pre>

<ul>
<li><p><code>(?&lt;!\w)</code> is zero width negative lookbehind pattern, making sure the desired match is not preceded by any alphanumerics</p></li>
<li><p><code>PG|SG|SF|PF|C</code> matches any of the desired patterns</p></li>
<li><p><code>(?!\w)</code> is zero width negative lookahead pattern making sure the match is not followed by any alphanumerics</p></li>
</ul>

<p><strong>Example:</strong></p>

<pre><code>In [7]: s = 'Chi\xa0SG, SF\xa0\xa0DTD'

In [8]: re.findall(r'(?&lt;!\w)PG|SG|SF|PF|C(?!\w)', s)
Out[8]: ['SG', 'SF']
</code></pre>

python regex string substring