【2017-08-28】字符串及文本的处理(三)

字符串的搜索、匹配以及特殊字符的处理

  • 忽略大小写搜索与替换文本
    直接给re模块中函数添加re.IGNORECAS参数,re.I为缩写形式
import re
str1="UPPER PYTHON, lower python, Mixed Python"
compilelist=re.findall("python",str1,flags=re.IGNORECASE)
print(compilelist)#结果:['PYTHON', 'python', 'Python']
  • 多行匹配模式
    通常出现在模式文本的内容跨越了多行,示例:获取/**/直接的文本
text1='''/* this is a
multiline comment */
 '''
text2="/* this is amultiline comment */"

pattern= re.compile(r'/\*(.*?)\*/')
compiletext1=pattern.findall(text1)#结果[]
compiletext2=pattern.findall(text2)结果['this is amultiline comment']
print(compiletext1)

解决方法
   a. 正则表达式中加上\n
   b. re模块中函数添加,re.DOTALL参数

#方法2
text='''/* this is a
multiline comment */
 '''
pattern= re.compile(r'/\*(.*?)\*/',re.DOTALL)
compiletext=pattern.findall(text)
print(compiletext)#结果:[' this is a\nmultiline comment ']

#方法1
pattern1= re.compile(r'/\*((?:.|\n)*?)\*/',re.DOTALL)#(?:.|\n)指定为非捕获组,仅仅用来做匹配,无组的概念
compiletext1=pattern.findall(text)
print(compiletext1)#结果:[' this is a\nmultiline comment ']
  • 最短匹配
    当使用正则表达式去匹配某个文本,有可能找到的为模式的最长匹配
    概念
       正则表达式的贪婪模式和非贪婪模式
       Python中使用正则表达式,默认为贪婪模式,即尽量匹配可能的最长文本,如果想要匹配最短文本,需要将贪婪模式变成非贪婪模式,即在被量词(*或+等)前面加上? ,寻找最短的可能匹配。通俗地说,贪婪模式有多少可匹配的取多少,非贪婪模式,找到就好了
import re
text='Computer says "no." Phone says "yes."'

pattern1=re.compile(r"\"(.*)\"")#贪婪模式
pattern2=re.compile(r"\"(.*?)\"")#非贪婪模式
compiledText1=pattern1.findall(text)
compiledText2=pattern2.findall(text)
print(compiledText1)#结果['no." Phone says "yes.']
print(compiledText2)#结果['no.', 'yes.']
  • 删除字符串开始或者结尾多余处的字符
    使用字符串方法
    strip() 删除开始和结尾的指定字符,默认是空格
    lstrip() 删除开始的指定字符,默认是空格
    rstrip() 删除结尾的指定字符,默认是空格
text="  we are ===     ----  "
text_all=text.strip()
text_right=text.rstrip()
text_left=text.lstrip()
text_other=text.rstrip("= - ")#可指定多个
#结果
      #原始字符串:测试  we are ===  结果
      #原始字符串:测试  we are ===     ----  结果
      #去掉开始和结尾空格:测试we are ===     ----结果
      #去掉结尾空格:测试  we are ===     ----结果
      #去掉开始空格:测试we are ===     ----  结果
      #去掉结尾空格:测试  we are结果

期待后续

你可能感兴趣的:(【2017-08-28】字符串及文本的处理(三))