Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I optionally match an additional substring with Python regular expressions?
    primarykey
    data
    text
    <p>I have a bunch of code in a text file on my computer. I'm interested in two different types of codes in the file. They are:</p> <pre><code>&lt;string&gt;objectiwant1 &lt;string2&gt;objectiwant2&lt;/string2&gt;&lt;/string&gt; </code></pre> <p>and</p> <pre><code>&lt;string&gt;objectiwant1 &lt;/string&gt; </code></pre> <p>The first one would return [(objectiwant1, objectiwant2)] (with more tuples if they exist) while the second one would return [(objectiwant1, None)].</p> <p>I'm trying to create a regular expression and the flawed code I have so far looks something like this:</p> <pre><code>regularexpression = r'&lt;string&gt;(.*) &lt;string2&gt;(.*)&lt;/string2&gt;' </code></pre> <p>I'm using "re.findall(regularexpression, file)" to return the data. Which returns what I want only if both string and string2 are used. Using:</p> <pre><code>regularexpression = r'&lt;string&gt;(.*) (&lt;string2&gt;(.*)&lt;/string2&gt;)|(&lt;/string&gt;) </code></pre> <p>Returns everything within the larger parentheses, sometimes twice (as opposed to only the data within (.*), which are necessary to seperate the statements I want to compare with the OR operator.</p> <p>I'm wondering whether or not there is something I could use to separate the parenthesis which wouldn't cause re.findall to output data twice and output so much data at once.</p> <p>I'm also wondering whether there is a way to use regex to output data if a statement is not fulfilled (so if the objectiwant2 doesn't exist, I get to choose what the output is).</p> <p>Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload