Regular expression to find text in specific section
<p>I have a regular expression problem.  My data is as follows:</p>

<pre><code>[Section 1]
   title = RegEx
   name = Joe
   color = blue
[Section 2]
   height = 101
   name = Gray
</code></pre>

<p>My question is can I write a regular expression to capture the 'name' key only from [Section 1]?  Essentially, capture a key that may exist in multiple places, but only capture it from a specific section.  I'll be implementing this in python.
Thanks</p>

<p>Just for reference, you could use the newer <code>regex</code> module and named capture groups:</p>

<pre><code>import regex as re

rx = re.compile("""
            (?(DEFINE)
               (?&lt;section&gt;^\[Section\ \d+\])
            )
            (?&amp;section)
            (?:(?!(?&amp;section))[\s\S])*
            ^\s*name\s*=\s*\K(?P&lt;name&gt;.+)$
            """, re.VERBOSE|re.MULTILINE)

string = """
[Section 1]
   title = RegEx
   name = Joe
   color = blue
[Section 2]
   height = 101
   name = Gray
"""

names = [match.group('name') for match in rx.finditer(string)]
print(names)
# ['Joe', 'Gray']
</code></pre>

<p>See <a href="https://regex101.com/r/sL2bK9/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>.</p>

python regex