Regular expression to match a specific pattern
<p>I have the following string:</p>

<pre><code>s = "&lt;X&gt; First &lt;Y&gt; Second"
</code></pre>

<p>and I can match any text right after <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> (in this case "First" and "Second"). This is how I already did it:</p>

<pre><code>import re
s = "&lt;X&gt; First &lt;Y&gt; Second"
pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)'  # lower and upper case X/Y will be matched
items = re.findall(pattern, s)
print items
&gt;&gt;&gt; [('X', ' First '), ('Y', ' Second')]
</code></pre>

<p>What I am now trying to match is the case without <code>&lt;&gt;</code>:</p>

<pre><code>s = "X First Y Second"
</code></pre>

<p>I tried this:</p>

<pre><code>pattern = r'([XxYy]) ([^\&lt;]+)'
&gt;&gt;&gt; [('X', ' First Y Second')]
</code></pre>

<p>Unfortunately it's not producing the right result. What am I doing wrong? I want to match X or x or Y or y PLUS one whitespace (for instance "X "). How can I do that?</p>

<p>EDIT: this is a possible string too:</p>

<pre><code>s = "&lt;X&gt; First one &lt;Y&gt; Second &lt;X&gt; More &lt;Y&gt; Text"
</code></pre>

<p>Output should be:</p>

<pre><code> &gt;&gt;&gt; [('X', ' First one '), ('Y', ' Second '), ('X', ' More '), ('Y', ' Text')]
</code></pre>

<p>EDIT2:</p>

<pre><code>pattern = r'([XxYy]) ([^ ]+)'
s = "X First text Y Second"
</code></pre>

<p>produces:</p>

<pre><code>[('X', 'First'), ('Y', 'Second')]
</code></pre>

<p>but it should be:</p>

<pre><code>[('X', 'First text'), ('Y', 'Second')]
</code></pre>

<p>Assuming that a the whitespace token to match is a single space character, the pattern is:</p>

<pre><code>pattern = r'([XxYy]) ([^ ]+)'
</code></pre>

python regex