In Python, how can I loop over all the matches of a regular expression on a string?

Viewed 8973

I want to do something (more than just substitution) with substrings matching a pattern in a longer string. If an assignment were an expression returning a value, as in C and most other programming languages, this would be (using C syntax with Python semantics):

  while ( match = re.search( pat, str ) ) {
       /* do something to the string, using the match object,
          in addition to removing or replacing the substring
       */
    }

or more verbosely, avoiding the use of an assignment as an expression:

for ( match = re.search( pat, str );
      match;
      match = re.search( pat, str ) ) {
   /* do something to the string, using the match object */
}

At least one of these is possible in most programming languages: C, C++, Java, Perl, Javascript, ... but neither of them seems to be possible in Python. Is there a pythonic equivalent (not involving a kludgey mess with a break or continue statement)?

1 Answers
Related