Skip to main content
 首页 » 编程设计

python正则表达式匹配逗号

2024年08月30日33bjzhanghao

在下面的字符串中,如何匹配包含逗号的单词

  1. --

    process_str = "Marry,had ,a,alittle,lamb" 
    import re 
     
    re.findall(r".*",process_str) 
    ['Marry,had ,a,alittle,lamb', ''] 
    
  2. --

    process_str="192.168.1.43,Marry,had ,a,alittle,lamb11" 
     
    import re 
    ip_addr = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",l)           
    re.findall(ip_addr,process_str1) 
    

    如何只查找除第一个逗号外的ip地址后面的词 即,outout 预计再次为 Marry,had ,a,alittle,lamb11

  3. 在上面的第二个示例中,如何查找字符串是否以数字结尾。

请您参考如下方法:

在第二个例子中,你只需要捕获(使用())ip后面的所有内容:

 import re 
 
 s = "192.168.1.43,Marry,had ,a,alittle,lamb11" 
 text = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},(.*)", s)[0] 
 // text now holds the string Marry,had ,a,alittle,lamb11 

要确定字符串是否以数字结尾,您可以使用以下命令:

re.match(".*\d$", process_str) 

也就是说,你匹配整个字符串(.*),然后回溯测试最后一个字符(使用$,它匹配字符串的结尾) ) 是一个数字。