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>You are iterating over the characters not the words, for that case you need to split your text.</p>

<p>Also you can do all of these jobs without regex:</p>

<pre><code>from string import ascii_uppercase

def check_word(word):
    return 'z' in word or 'pt' in word or word.endswith('ize') or word.startswith(tuple(ascii_uppercase))

[w for w in text6.split() if check_word(w)]
</code></pre>

<p>Demo :</p>

<pre><code>&gt;&gt;&gt; text6 = "here are some example: appease dance offensive xxxize executive and other extra words optimum Python"
&gt;&gt;&gt; [w for w in text6.split() if check_word(w)]
['xxxize', 'optimum', 'Python']
</code></pre>

<p>For the last condition (<em>the words starts with 1 and only 1 capital letter</em>) if you don't want any upper case in word except the first one you can add (<code>word[1:].islower()</code>) to <code>check_word</code> function:</p>

<pre><code>def check_word(word):
    return 'z' in word or 'pt' in word or word.endswith('ize') or (word.startswith(tuple(ascii_uppercase)) and word[1:].islower())
</code></pre>

<p><em>Note</em>: If you want to separate the words with multiple delimiter or based on another condition you can use <code>re.findall()</code> in order to find the words.</p>

<p>For example the following regex will wind the words contain word characters:</p>

<pre><code>re.findall(r'\b\w+\b', my_str)
</code></pre>

python regex