Home  >  Article  >  Backend Development  >  python regular expression learning summary

python regular expression learning summary

高洛峰
高洛峰Original
2017-01-12 16:28:101104browse

The way to implement regular expression in Python is through the re (abbreviation for regular expression) module. You can call various methods of the re module to achieve different functions. Let’s talk about how to implement regular expression in Python through Which methods can be called by the re module, and what are the functions of these methods; there are also examples of regular expressions and the meanings of various special symbols:

 1. re.sub and replace:

The full spelling of sub is substitute, which means to replace; now that we know it is to replace, it is easy to use it in examples. In fact, replace also means to replace, but their usage is not the same. , let’s use an example to explain their similarities and differences in detail:

>>> import re
>>> str1 = 'Hello 111 is 222'
>>> str2 = str1.replace('111','222')
>>> print(str2)
Hello 222 is 222
>>>

This is a simple example. If it is the following situation, replace all the numbers with 222, then use replace to implement it It is more troublesome, but it is relatively simple to implement using the sub method of the re module: (If it is a more complex operation, it may not be possible to use replace.)

>>> import re
>>> str1 = 'Hello 123 is 456'
>>> str2 = re.sub('\d+','222',str1)
>>> print(str2)
Hello 222 is 222
>>>

 2. re.search() and re.match():

Match: Only matches the regular expression from the beginning of the string. If the match is successful, it returns matchobject, otherwise it returns none.

Search: Will All strings in the string try to match the regular expression. If all strings are not matched successfully, none is returned, otherwise matchobject.

The following example illustrates the similarities and differences between match and search. , also shows that in actual applications, search is still used more:

import re
str = 'helloword,i am alex'
if not re.match('word',str):
print('cannot match')
print(re.match('hello',str1).group())
print(re.search('word',str1).group())
#显示结果
cannot match
hello
word


## 3. re.split:


In Python, if you want to split a string, you only need to call the split method of str to achieve it. However, this split can only be split based on a certain character. If you want to specify multiple characters at the same time for splitting If so, it cannot be realized.


Fortunately, the re module also provides the split method to split strings, and this method is more powerful. It can split based on multiple characters at the same time. Let’s take a look at str separately. What is the difference between split and re split:

str1 = 'helloword,i;am\nalex'
str2 = str1.split(',')
print(str2)
import re
str3 = re.split('[,|;|\n]',str1)
print(str3)
#下面是不同的输出结果
['helloword', 'i;am\nalex']
['helloword', 'i', 'am', 'alex']


## From this we can see the authenticity of the above.


4. findall:


The findall method basically appears at the same time as the compile method. Their usage is:


First Convert the string form of a regular expression into a pattern instance by compile, and then use the pattern instance to call the findall method to generate a match object to obtain the result. Before combining them, let's first look at the presets in the regular expression. Special character meaning:


\d matches any decimal number; it is equivalent to class [0-9].

\D matches any non-numeric character; it is equivalent to class [^0-9].

  \s matches any whitespace character; it is equivalent to class ["t"n"r"f"v].

  \S matches any non-whitespace character; it is equivalent to class [^ "t"n"r"f"v].

\w matches any alphanumeric character; it is equivalent to class [a-zA-Z0-9_].

\W matches any non-alphanumeric character; it is equivalent to class [^a-zA-Z0-9_].


After reading the meanings of these special characters, let’s give another example to illustrate the above argument:

import re
str1 = 'asdf12dvdve4gb4'
pattern1 = re.compile('\d')
pattern2 = re.compile('[0-9]')
mch1 = pattern1.findall(str1)
mch2 = pattern2.findall(str1)
print('mch1:\t%s'% mch1)
print('mch2:\t%s'% mch2)
#输出结果
mch1: ['1', '2', '4', '4']13 mch2: ['1', '2', '4', '4']


The above two Each example can well illustrate the above argument, and also shows that the special character \d is indeed the same as [0-9]. It can be seen from the output results, then if you don’t want to split each number Divide it into one element and put it in the list, but if you want to output 12 as a whole, then you can do this: (It is achieved by adding a + sign after \d. The + sign here means to put a Or multiple connected decimal numbers are output as a whole)

import re
str1 = 'asdf12dvdve4gb4'
pattern1 = re.compile('\d+')
pattern2 = re.compile('[0-9]')
mch1 = pattern1.findall(str1)
mch2 = pattern2.findall(str1)
print('mch1:\t%s'% mch1)
print('mch2:\t%s'% mch2)
#输出结果
mch1: ['12', '4', '4']
mch2: ['1', '2', '4', '4']


Let’s give another small example. This example combines special characters and the sub function of re to realize the string. All spaces are removed:

import re
str1 = 'asd \tf12d vdve4gb4'
new_str = re.sub('\s*','',str)
print(new_str)
#输出结果
asdf12dvdve4gb4


5. Metacharacters:


What we usually call binary The characters are; 2 metacharacters: . ^ $ * + ? { } [ ] | ( ) \


The metacharacters we first examine are "[" and "]". They are often used to specify a character category, which is a character set you want to match. Characters can be listed individually, or two given

characters separated by a "-" sign can be used to represent a character range. For example, [abc] will match any character among "a", "b", or "c"; you can also use the interval [a-c] to represent the same character set, which has the same effect as the former. If you only want to match lowercase letters, then RE should be written [a-z]. Metacharacters have no effect in categories. For example, [akm$] will match any of the characters "a", "k", "m", or "$"; "$" is usually used as a metacharacter, but within the character class, its characteristics are removed, Revert to the normal character

character.

    []:元字符[]表示字符类,在一个字符类中,只有字符^、-、]和\有特殊含义。字符\仍然表示转义,字符-可以定义字符范围,字符^放在前面,表示非.(这个在上面的特殊字符示例中也有提现),

    + 匹配+号前内容1次至无限次
    ? 匹配?号前内容0次到1次
    {m} 匹配前面的内容m次
    {m,n} 匹配前面的内容m到n次

    下面通过一个小例子,来阐述一下上面的字符在元字符[]中的使用:(在下面的这个例子中,要注意的有两点:一是在\d+后面的?号的含义,二是在匹配的前面加上了一个字符r,其实在这个示例中,加与不加都可以显示一样的结果)

>>> import re
>>> print(re.findall(r"a(\d+?)","a123b"))
['1']
>>> print(re.findall(r"a(\d+)","a123b"))
['123']
>>>


以上所述是小编给大家介绍的python 正则表达式学习小结,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多python 正则表达式学习小结相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn