正则表达式需要用到re模块:
① re 模块中有一个函数findall(),在pycharm3.4.1中是这样解释的:
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
② re 模块中有一个函数compile(),在pycharm3.4.1中是这样解释的:
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
实例如下:
import re
str_test = 'abcdefgHABC123456中华人名共和国'
shuzi_regex = re.compile(r'[0-9]')
zimu_regex = re.compile(r'[a-zA-z]')
hanzi_regex = re.compile(r'[\u4E00-\u9FA5]')
print('输入字符串:',str_test)
#findall获取字符串中所有匹配的字符
num_list = shuzi_regex.findall(str_test)
print('包含的数字:',shuzi_list)
zimu_list = zimu_regex.findall(str_test)
print('包含的字母:',zimu_list)
hanzi_list = hanzi_regex.findall(str_test)
print('包含的汉字:',hanzi_list)
#“\u4e00”和“\u9fa5”是unicode编码,并且正好是中文编码的开始和结束的两个值。详情在此:https://blog.csdn.net/hherima/article/details/9045861
#Python中字符串前面加上 r 表示原生字符串,\u表示unicode编码
与大多数编程语言相同,正则表达式里使用"“作为转义字符,这就可能造成反斜杠困扰。
假如你需要匹配文本中的字符”",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。
Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\“表示。同样,匹配一个数字的”\d"可以写成r"\d"。
有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。