Looking for a regular expression used on variable string
<p>I have a string that can vary slightly:</p>

<pre><code>str1 = "[X] text [Y] abc123"
str1 = "(X ) text [y ]  abc123"
str1 = "(x) text (Y)        abc123"
str1 = "(X ) text   (Y)  abc123"
str1 = "(X ) text [Y ]  abc123"
str1 = "[X]   text333 [y]  abc123222"
</code></pre>

<p>so basically X and Y are static and they can either be between <code>()</code> or <code>[]</code>. My problem is, that there can be some white spaces as well. X and Y with bracket can be assumed as delimiter to capture group 1. I am currently asking myself how to parse "text" and "abc123" in the most reliable way. How would you do it? "text" and "abc123" are variable strings. I want to use them further</p>

<p>The regex you want could be <code>r'(?i)\s*(?:\[\s*(?:X|Y)\s*\]|\(\s*(?:X|Y)\s*\))\s*'</code>
This assumes that <code>[]</code> or <code>()</code> pairs must match, and that (as you show in your example) X and Y can be either upper or lower case (or mixed case, if <code>X</code> or <code>Y</code> is a longer token).  It does not require that <code>[X]</code> preceed <code>[Y]</code>.</p>

<p>If you use this regex to split any of your <code>str1</code> values, you'll get an array of 3 elements (<code>['', 'text', 'abc123']</code>).</p>

<pre><code>strs = [ "[X] text [Y] abc123",
         "(X ) text [y ]  abc123",
         "(x) text (Y)        abc123",
         "(X ) text   (Y)  abc123",
         "(X ) text [Y ]  abc123",
         "[X]   text333 [y]  abc123222", ]

for s in strs:
    print(re.split(r'(?i)\s*(?:\[\s*(?:X|Y)\s*\]|\(\s*(?:X|Y)\s*\))\s*', s))
</code></pre>

<p>prints</p>

<pre><code>['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text333', 'abc123222']
</code></pre>

python regex