I do not get what expected on a regex expression
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p>

<p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p>

<pre><code>L2=[w for w in text6 if re.search(r".*[z]|.*[p][t]|[ize]$",w)
</code></pre>

<p>Another question building up on the previous exercise: I need to add a new alternative condition i.e. that the words starts with 1 and only 1 capital letter.</p>

<p>I wrote</p>

<pre><code>L2=[w for w in text6 if re.search(r"[A-Z]{1}|.*[z]|.*[p][t]|[ize]$",w)
</code></pre>

<p>It includes also upper case words (i.e all characters in capital letter)</p>

<p>Could any one help in these 2 questions?</p>

<p>Thank you in advance</p>

<p>mauro</p>

<p>I would suggest a non-regex approach here, since regex seems more complicated than this use case demands.</p>

<p>For one, you can get rid of the "ends in <code>ize</code>" constraint, because that falls under any words with <code>z</code> in it.</p>

<pre><code>text6 = [
    'appease', 'dance', 'offensive', 'executive',
    'inept', 'zoo', 'Inept', 'Zoo', 'INept', 'ZOo']
</code></pre>

<p>For just matching words with lowercased <code>pt</code> or <code>z</code>:</p>

<pre><code>[w for w in text6 if 'pt' in w or 'z' in w]  # ['inept', 'zoo', 'Inept', 'INept']
</code></pre>

<p>For matching the above cases as well as only capitalized words:</p>

<pre><code>[w for w in text6 if w.istitle() and ('pt' in w or 'z' in w)]  # ['Inept']
</code></pre>

<p>Of course, it may be better to write a function that abstracts this logic out:</p>

<pre><code>def meets_criteria(word):
    return word.istitle() and ('pt' in word or 'z' in word)

[w for w in text6 if meets_criteria(w)]
</code></pre>

<p>If you want to also match words starting with <code>Z</code> and <code>Pt</code>, you can check membership in <code>w.lower()</code> instead.</p>

python regex