Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regular expression match comma

Tags:

python

regex

In the following string,how to match the words including the commas

  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)
    

    How to find the words after the ip address excluding the first comma only i.e, the outout again is expected to be Marry,had ,a,alittle,lamb11

  3. In the second example above how to find if the string is ending with a digit.

like image 622
Rajeev Avatar asked Oct 09 '22 04:10

Rajeev


1 Answers

In the second example, you just need to capture (using ()) everything that follows the 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

To find out if the string ends with a digit, you can use the following:

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

That is, you match the entire string (.*), and then backtrack to test if the last character (using $, which matches the end of the string) is a digit.

like image 74
João Silva Avatar answered Oct 12 '22 20:10

João Silva