How to count the number of commas in a string using regular expression in python?
Question: I have a string in the following format:

    
    
    str ="India,USA,Australia,Japan,Russia"
    

I want to extract the word present after third comma by counting the number of
commas using regular expression in python.

desired output:`Japan`


Answer: You can do that with a regular expression with something like

    
    
    ([^,]*,){3}([^,]*)
    

with the meaning

  * `[^,]*` Zero or more chars but no commas
  * `,` a comma
  * `{3}` the previous group must be repeated three times
  * `[^,]*` Zero or more chars but no commas

the second group will be the fourh comma-separated value

    
    
    import re
    text = "India,USA,Australia,Japan,Russia"
    m = re.match("([^,]*,){3}([^,]*)", text)
    if m:
        print m.group(2)
    

In this specific case however it would be much simpler to just split on commas
and taking the fourth value:

    
    
    print text.split(',')[3]
    

