-4

I am trying to match brackets using regex in python:

(a (dcsd)) () 

I dont have internet on my desktop at the moment so I cant download new libraries. What is the best way of doing this when regex has no recursive features in python?

More clearly, and for a particular user who cannot read, I do not have internet on my main computer, just some mobile internet that I am using to post this question. I was hoping that someone could suggest a manual algorithm for finding the contents of matched brackets as the only answers I have found using the almighty google use separate libraries.

In that example I would need the result 'a' 'dcsd'

8
  • 3
    i am sorry,because there is no support of recursion in re library..you need regex library..BTW, how are you asking question without internet? Commented Jun 26, 2016 at 14:21
  • 1
    @rock321987: Good point! Commented Jun 26, 2016 at 14:22
  • If you just want to verify they are balanced - without a regular expression: s.count('(') == s.count(')') Commented Jun 26, 2016 at 14:36
  • 1 - I have no internet on the desktop I need to the run program from. I of course have it on my phone. 2 - Google isnt helping because python does not seem to support recursive regex - hence I am asking for an alternative algorthim that does not involve downloading a new library - something I could not find elsewhere on here, obviously I googled it first Commented Jun 26, 2016 at 14:44
  • @user1212520 you can use stack.. Commented Jun 26, 2016 at 14:54

1 Answer 1

1

You cannot match brackets using regex, this sentiment is echoed by the comments you have received.

Regular expressions (regex) is a Chomsky Type 3 grammar, whereas finding matching tokens in a string requires a Chomsky Type 2 grammar (or above). Regular expressions have the same descriptive power as a finite automata.

To find matching tokens such as quote symbols, parentheses, braces etc. requires a computational model capable of describing grammars of Chomsky Type 2, namely a pushdown automaton. You might better recognize this as having a "stack".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.