zoukankan      html  css  js  c++  java
  • 正则表达式

     1 import re
     2 
     3 # ============= 笔记 =================
     4 '''
     5 re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
     6 而re.search匹配整个字符串,直到找到一个匹配。
     7 
     8 
     9 # ==================================== #
    10 '''
    11 #  p:模式  s:要匹配的字符串
    12 
    13 
    14 def match(p, s):
    15     matchobj = re.search(p, s)
    16     if matchobj:
    17         print('匹配成功')
    18         print("匹配的字符串是:", matchobj.group())
    19         #print("匹配的字符串的索引是:",matchobj.start(),matchObj.end())
    20     else:
    21         print("匹配失败")
    22 
    23 
    24 def sub(in_file, out_file):
    25     with open(out_file, "w", encoding="utf-8") as f_write:
    26         for line in open(in_file):
    27             sub_line = re.sub('NV', 'GN', line)
    28             print(sub_line)
    29             f_write.write(sub_line)
    30         f_write.close()
    31 
    32 
    33 pattern = 'abc'
    34 string = 'hello abc dog'
    35 match(pattern, string)
    36 
    37 in_file = './in.txt'
    38 out_file = './out.txt'
    39 sub(in_file, out_file)
  • 相关阅读:
    ActiveMQ学习第八篇:Consumer
    ActiveMQ学习第七篇:Messaage
    线性判别分析LDA
    逻辑回归
    那些年,曾踩过的Spark坑
    HBase表创建、删除、清空
    python的多线程
    python的多进程
    python实现读写txt文件
    python的封包和解包
  • 原文地址:https://www.cnblogs.com/wt-seu/p/11269626.html
Copyright © 2011-2022 走看看