Python之正则表达式进阶篇

正则表达式里面最恶心的就是‘\’了。下面第一种是没有使用r的写法。

# -*- coding: utf-8 -*-

import sys
import os  # 目录操作
import re  # 正则表达式

mydir = 'F:\Code_Practice\Python_Project\NAO_PRO'

if __name__ == "__main__":
    # 将正则表达式编译成Pattern对象 
    pattern = re.compile('F:\\\\Code_Practice\\\\Python_Project\\\\NAO_PRO(\s+)')
    pattern1 = re.compile("^(F:\\\\Code_Practice\\\\Python_Project\\\\NAO_PRO\\\\)(\d*)")
    res1 = pattern1.search('F:\\Code_Practice\\Python_Project\\NAO_PRO\\7941520')
    if res1:
        print res1.group(0),res1.group(1),res1.group(2)
    test_str = 'F:\\Code_Practice\\Python_Project\\NAO_PRO\\sdfdd'
    res = pattern.search(test_str)
    if res:
        result1 = res.group(0) + "\n"
        print result1
    else:
        print 'Gosh\n'
    print test_str
    # print pattern

下面一个例子我觉得很棒的东西,就是遍历某个目录,把里面的文件都取出来。

# -*- coding: utf-8 -*-

import sys
import os  # 目录操作
import re  # 正则表达式

mydir = 'F:\Code_Practice\Python_Project\NAO_PRO'

if __name__ == "__main__":
#   将正则表达式编译成Pattern对象 
    pattern = re.compile(r'^(F:\\Code_Practice\\Python_Project\\NAO_PRO\\)(\w+).(\w+)')
#   pattern = re.compile('F:\\\\Code_Practice\\\\Python_Project\\\\NAO_PRO\\\\(\w+).(\w+)')
#   re.compile(r'^(F:\\Code_Practice\\Python_Project\\NAO_PRO\\)(\w+).(\w+)')
#   和re.compile(r'F:\\Code_Practice\\Python_Project\\NAO_PRO\\(\w+).(\w+)') 不一样的地方是加了^之后
#   group(1)就是^里面的内容,否则group(1)是(\w+)里面的东西
#   在这里的话有没有r还是有区别的,有r的话那么'\'只要'\\',否则就是'\\\\'
    pattern1 = re.compile(r"^(F:\\\\Code_Practice\\\\Python_Project\\\\NAO_PRO\\\\)(\w+).(\w+)")
    res = pattern1.search(r'F:\\Code_Practice\\Python_Project\\NAO_PRO\\7941520.sddd')
    if res:
        print res.group(2) +'.'+res.group(3)
    else:
        print 'test fail'
#   test_str = 'F:\\Code_Practice\\Python_Project\\NAO_PRO\\sdfdd'
#   res = pattern.search(test_str)
#   if res:
#       result1 = res.group(1) + "\n"
#       print result1
#   else:
#       print 'Gosh\n'
#   print test_str
    # print pattern
    for filename in os.listdir(mydir):
        filepath = os.path.join(mydir, filename)
        if os.path.isfile(filepath):
            print str(filepath)
            s1 = pattern.search(str(filepath))  
            # m = re.match(r'^(F:\\Code_Practice\\Python_Project\\NAO_PRO\\)+\S+)', filepath)
            if s1:  
                result = s1.group(1) + '.' + s1.group(2)
                print result
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值