zoukankan      html  css  js  c++  java
  • python正则表达式里引入变量

    import re
    
    def reg_exp(senten):
    	jiqiren = "阿童木"
    	matchObj1 = re.search( r'(你(.*?)(男|女))|(机器(.*?)(男|女))|((.*?)(男的|男|女的|女))|(.*?)(什么(.*?)(性别))', senten, re.M|re.I)
    	matchObj2 = re.search( r''+ str(jiqiren) + '(.*?)(名字|姓名|叫什么|叫什么名|叫什么名字)', senten, re.M|re.I)
    
    	
    	if matchObj1:
    		print ("我是男的啊")
    	elif matchObj2:
    		print ("我叫阿童木")
    	else:
    		print ("No match!!")
    
    
    if __name__=="__main__":
    	senten = "阿童木的名字"
    	reg_exp(senten)
    

     注意

    '+ str(jiqiren) + ' 要和r' 靠紧写。  这也验证了,正则表达式也可以写在txt里面,然后一行行读出来和r'配合。我们一起来见证下。之前搞了好久,这次灵感来了,分分钟解决

     1 import re
     2 
     3 def reg_exp(senten):
     4     f = open("reg.txt")           
     5     lines = f.readlines()#读取全部内容  
     6     for line in lines:
     7         print (line)
     8 
     9         matchObj1 = re.search( r''+ line +'', senten, re.M|re.I)
    10         if matchObj1:
    11             print ("我是男的啊")
    12         else:
    13             print ("No match!!")
    14 
    15 
    16 if __name__=="__main__":
    17     senten = "你是男"
    18     reg_exp(senten)

    其中reg.txt的内容是  (你(.*?)(男|女))|(机器(.*?)(男|女))|((.*?)(男的|男|女的|女))|(.*?)(什么(.*?)(性别))    运行结果如下:

     参考文章:

      https://www.cnblogs.com/yangshuo/archive/2013/06/06/3120595.html

  • 相关阅读:
    HDU 2476 String painter (*区间DP+基础Dp)
    hdoj 1405 The Last Practice
    hdu 2715 Herd Sums
    hdu 3617 Happy 2009
    hdu 1062 Text Reverse
    hdu 2716 Message Decowding
    hdu 1597 find the nth digit
    hdoj 1229 还是A+B
    hdu 1877 又一版 A+B
    hdoj 2045 不容易系列之(3)—— LELE的RPG难题
  • 原文地址:https://www.cnblogs.com/www-caiyin-com/p/8302675.html
Copyright © 2011-2022 走看看