Use regular expressions to group string sample code and regular expression sample code
Preface
In recent work, I encountered a problem. The requirement is that a string of '000000' <'should be taken out of a coherent part to obtain ['1', '22 ', '123456', '<'] is a list that can be used to traverse strings and compare the last one with the previous one. This is really troublesome! I thought of the other two methods. I will not talk much about them. Let's take a look at the detailed sample code:
I. Actually, you can use the groupby () method of the itertools module to handle the problem:
import itertools Str = '122333<<<<' Lst = [] for key,group in itertools.groupby(s): Lst.append(list(group)) print map(lambda x: ''.join(x), Lst)
The above processing is more skillful and can also get the desired output result.
['1', '22', '123', '<']
2. But more cool, it is more skillful to use regular expressions for processing:
import re Str = '122333<<<<' Lst = [] Pat = re.compile(r'((.)\2*)') Rst = [x[0] for x in re.findall(Pat, Str)] print Rst
Note:
1. (.) #. match any character; (.) grouping to facilitate reverse reference
2. \ 2 * # \ 2 reverse references to the parentheses; * Indicates 0 to multiple;
3. (.) \ 2 *) # connecting is a group of any one or more characters;
4. (.) \ 1 * # This method can retrieve the unique values ['1', '2', '3', '<'];
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.