Python Regular Expression advanced application example

Source: Internet
Author: User
First, the reason for writing this article is that I played a website in the past two days.   Http://www.checkio.org  It is interesting and challenging to use python for question, question, and communication.
------------ Enter the topic --------------------------
  The question of processing a string is as follows:Http://www.checkio.org/mission/implementation/1088/python-27/ In short, the input is a string, and the output is also a string. What we need to do is add a decimal point to the integer in the input every three digits.
Test cases: Assert checkio ('20140901') = '1970. 123'  Assert checkio ('20140901') = '20160901'  Assert checkio ('20140901') = '9. 123'  Assert checkio ('2014. 20180101') = '2014. 20180101'  Assert checkio ('price is 5799 ') = 'price is 5.799'  Assert checkio ('He was born in 1966th ') = 'He was born in 1966th'
  The question should be clearly expressed. I wrote a piece of code, which is about 20 ~ Use a regular expression to extract the number from the 30 rows, change the number, and enter the regular expression. The trouble is that the length is increased after the string is modified. Therefore, when extracting the string, you must process the current insertion position and the like yourself.
  After passing this question, I read the best solution:  Def checkio (txt ):  '''  String with comma separated numbers, which inserted after every third digit from right to left '''  Return re. sub (R '(? <= \ D )(? = (\ D) + \ B) ','. ', STR (txt ))
  After reading this article, I found myself not familiar with Python's enhanced regular expressions. I read this article and completed my homework:  Introduction to Python Regular Expressions   Http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html      The above solution is very clever. Note :(? =...) This matching mode does not consume characters, so it will form a loop matching, just to achieve the goal. I mean: if it is not a loop match, the next word may continue after a decimal point is added.
  After testing ,(? <=...) This special structure has a restriction -- it must be of a fixed length. If you write (? <= .*?) For this condition, Python reports an exception.
------------ Re. sub function -------------------- The solution to this question is clever. Of course, it also means that it is special, and its versatility is not strong.  Go back to my previous code and paste it out:Def checkio (txt ): '''  String with dot separated numbers, which inserted after every third digit from right to left  '''  L = []  Beg = 0  For E in re. finditer (R' \ B \ D + \ B ', txt ):  P1, p2 = E. span ()  L. append (txt [beg: P1])    S = TXT [P1: P2]  S2 = []  For I in range (LEN (S)-1,-1,-1 ):  S2.append (s [I]) If (LEN (S)-I) % 3 = 0 and I! = 0:
  S2.append ('.')  S2.reverse ()  S = ''. Join (S2)  L. append (s)    Beg = P2  L. append (txt [beg:])  Print ''. Join (l)  Return ''. Join (l)  The long section in the middle is to add a decimal point to the string. If you do not know it, then the extra part is several variables such as l, beg, P1, and P2 and their calculation.  After careful consideration of RE. findall and RE. sub, we found that they are not found in the same way, mainly because they are not handled in the group enclosed in parentheses. I have been wondering about this problem before. Today, I suddenly realized:
  Repl, the second parameter of RE. sub, can be a function!
  If you customize a function change (MATCH), the underlying layer will call this change function when you find the appropriate pattern when using re. sub. A parameter is a match object that records things such as group and span. Processing this match object returns a string, and the underlying layer will help you replace this string.  It is not easy to explain. Just try it.
  I used this method to modify the previously processed functions of the MB file, which is much simpler. The Interface Design of the RE. sub function is natural and worth learning. I didn't think it could be used in the past, so I had to blame myself.

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.