Use regular expressions to group string sample code and regular expression sample code

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.