Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3456100
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T09:41:41+00:00 2026-05-18T09:41:41+00:00

Apparently this problem comes up fairly often, after reading Regular expression to detect semi-colon

  • 0

Apparently this problem comes up fairly often, after reading

Regular expression to detect semi-colon terminated C++ for & while loops

and thinking about the problem for a while, i wrote a function to return the content contained inside an arbitrary number of nested ()

The function could easily be extended to any regular expression object, posting here for your thoughts and considerations.

any refactoring advice would be appreciated

(note, i’m new to python still, and didn’t feel like figuring out how to raise exceptions or whatever, so i just had the function return ‘fail’ if it couldin’t figure out what was going on)

Edited function to take into account comments:

def ParseNestedParen(string, level):
    """
    Return string contained in nested (), indexing i = level
    """
    CountLeft = len(re.findall("\(", string))
    CountRight = len(re.findall("\)", string))
    if CountLeft == CountRight:
        LeftRightIndex = [x for x in zip(
        [Left.start()+1 for Left in re.finditer('\(', string)], 
        reversed([Right.start() for Right in re.finditer('\)', string)]))]

    elif CountLeft > CountRight:
        return ParseNestedParen(string + ')', level)

    elif CountLeft < CountRight:
        return ParseNestedParen('(' + string, level)

    return string[LeftRightIndex[level][0]:LeftRightIndex[level][1]]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T09:41:42+00:00Added an answer on May 18, 2026 at 9:41 am

    You don’t make it clear exactly what the specification of your function is, but this behaviour seems wrong to me:

    >>> ParseNestedParen('(a)(b)(c)', 0)
    ['a)(b)(c']
    >>> nested_paren.ParseNestedParen('(a)(b)(c)', 1)
    ['b']
    >>> nested_paren.ParseNestedParen('(a)(b)(c)', 2)
    ['']
    

    Other comments on your code:

    • Docstring says “generate”, but function returns a list, not a generator.
    • Since only one string is ever returned, why return it in a list?
    • Under what circumstances can the function return the string fail?
    • Repeatedly calling re.findall and then throwing away the result is wasteful.
    • You attempt to rebalance the parentheses in the string, but you do so only one parenthesis at a time:
    >>> ParseNestedParen(')' * 1000, 1)
    RuntimeError: maximum recursion depth exceeded while calling a Python object
    

    As Thomi said in the question you linked to, “regular expressions really are the wrong tool for the job!”


    The usual way to parse nested expressions is to use a stack, along these lines:

    def parenthetic_contents(string):
        """Generate parenthesized contents in string as pairs (level, contents)."""
        stack = []
        for i, c in enumerate(string):
            if c == '(':
                stack.append(i)
            elif c == ')' and stack:
                start = stack.pop()
                yield (len(stack), string[start + 1: i])
    
    >>> list(parenthetic_contents('(a(b(c)(d)e)(f)g)'))
    [(2, 'c'), (2, 'd'), (1, 'b(c)(d)e'), (1, 'f'), (0, 'a(b(c)(d)e)(f)g')]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

A coworker of mine has this problem, apparently after installing Re#, which seems totally
Apparently using the URL is no good - why is this the case, and
Question: I have a question that is apparently not answered by this already-asked Bash
Many websites, including this one, add what are apparently called slugs - descriptive but
I've just solved another *I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-*issue (sigh). Does anybody know a good way to verify
I need to change an element's ID using jQuery. Apparently these don't work: jQuery(this).prev(li).attr(id)=newid
Today I stumpled upon the shadowCopyBinAssemblies option in the hostingEnvironment tag. Appearently this attribute
Apparently xrange is faster but I have no idea why it's faster (and no
Apparently we use the Scrum development methodology. Here's generally how it goes: Developers thrash
Apparently there's a lot of variety in opinions out there, ranging from, " Never!

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.