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 8007743
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T17:55:45+00:00 2026-06-04T17:55:45+00:00

I’m wondering if something like this is possible in python (3.2, if that’s relevant).

  • 0

I’m wondering if something like this is possible in python (3.2, if that’s relevant).

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b)

Where the behavior is:

  • if the regex matches, the regex groups get assigned to a and b
    • if there’s a mismatch there, it’d throw an exception
  • if the match is None, it would just bypass the context entirely

My goal here is basically an extremely concise way of doing the contextual behavior.

I tried making the following context manager:

import re

class assign_match(object):
    def __init__(self, regex, string):
        self.regex = regex
        self.string = string
    def __enter__(self):
        result = re.match(self.regex, self.string)
        if result is None:
            raise ValueError
        else:
            return result.groups()
    def __exit__(self, type, value, traceback):
        print(self, type, value, traceback) #testing purposes. not doing anything here.

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b) #prints abc def
with assign_match('(abc)g', 'abcdef') as (a, b): #raises ValueError
    print(a, b)

It actually works exactly as desired for the case when the regexes match, but, as you can see, it throws the ValueError if there’s no match. Is there any way I can get it to “jump” to the exit sequence?

Thanks!!

  • 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-06-04T17:55:47+00:00Added an answer on June 4, 2026 at 5:55 pm

    Ah! Perhaps explaining it on SO clarified the problem for me. I just use an if statement instead of a with statement.

    def assign_match(regex, string):
        match = re.match(regex, string)
        if match is None:
            raise StopIteration
        else:
            yield match.groups()
    
    for a in assign_match('(abc)(def)', 'abcdef'):
        print(a)
    

    Gives exactly the behavior I’d like. Leaving this here in case other people want to benefit from it. (Mods, if it’s not relevant, feel free to delete, etc.)

    EDIT: Actually, this solution comes with one fairly large flaw. I’m doing this behavior within a for-loop. So this prevents me from doing:

    for string in lots_of_strings:
        for a in assign_match('(abc)(def)', string):
            do_my_work()
            continue # breaks out of this for loop instead of the parent
        other_work() # behavior i want to skip if the match is successful
    

    Because the continue now breaks out of this loop instead of the parent for loop. If anyone has suggestions, I’d love to hear!

    EDIT2: Alright, figured it out for real this time.

    from contextlib import contextmanager
    import re
    
    @contextmanager
    def assign_match(regex, string):
        match = re.match(regex, string)
        if match:
            yield match.groups()
    
    for i in range(3):
        with assign_match('(abc)(def)', 'abcdef') as a:
    #    for a in assign_match('(abc)(def)', 'abcdef'):
            print(a)
            continue
        print(i)
    

    Sorry for the post – I swear I was feeling really stuck before I posted. 🙂 Hopefully someone else will find this interesting!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I have some data like this: 1 2 3 4 5 9 2 6
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I would like to count the length of a string with PHP. The string
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.

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.