HackerRank Python Solution - Regex and Parsing - Group(), Groups() & Groupdict()

  • A group() expression returns one or more subgroups of the match.
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0)       # The entire match 
>>> m.group(1)       # The first parenthesized subgroup.
>>> m.group(2)       # The second parenthesized subgroup.
>>> m.group(3)       # The third parenthesized subgroup.
>>> m.group(1,2,3)   # Multiple arguments give us a tuple.
('username', 'hackerrank', 'com')
  • A groups() expression returns a tuple containing all the subgroups of the match.
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.groups()
('username', 'hackerrank', 'com')
  • A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}
  • You are given a string S.
  • Your task is to find the first occurrence of an alphanumeric character in S (read from left to right) that has consecutive repetitions.
Input Format:
  • A single line of input containing the string S.
  • 0 < len(S) < 100
Output Format:
  • Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
Sample Input:

Sample Output:

  • .. is the first repeating character, but it is not alphanumeric.
  • 1 is the first (from left to right) alphanumeric repeating character of the string in substring 111.

import re
s = input()
m = re.search(r"([a-zA-Z0-9])\1", s)

if m:
Note: The problem statement is given by hackerrank.com but the solution is generated by the Geek4Tutorial admin. We highly recommend you solve this on your own, however, you can refer to this in case of help. If there is any concern regarding this post or website, please contact us using the contact form. Thank you!

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...