Using Regex To Split A String Recursively
How do I go from this input to the following output?
word = "f(a(a,b), b(c,d)) def convert(word): ... return fixed_word print(convert(word)) >> ["f", "(a(a,b), b(c,d))"]
Additionally, how would I go about recursively creating the list? For example if I want the list to instead look like:
word = "f(a(a,b), b(c,d)) print(convert(word)) >> ["f", "a", "a", "b", "b", "c", "d"]
I've tried using regex for this but haven't managed to come up with a valid solution so any help would be much appreciated.
I'm not completely sure what you wish to achieve but for your first example i would recommend something like:
mo = re.match(re.compile(r"(\w)(\(.*\))"), word) # f (a(a,b)...) result = list(mo.groups()) # or just mo.groups() if it can be a tuple instead of a list
For the second one I would refer you to the other answers you've gotten if you only want to split single characters. However if you need to have multiple characters you could split the string on any non-word character like:
word = "f(a(ab,bc), ba(c,d))" result = re.split(re.compile(r"\W+"), word) # ['f', 'a', 'ab', 'bc', 'ba', 'c', 'd', '']
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module