def __call__(self, args, data=None, **kwargs): if len(args) >= 2: if args[1] == '2' and len(args) == 2: return "8! Whoa, that's 2Cubed!" numbers = findall( r"( [0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)", ' ' + ' '.join(args[1:]) + ' ' ) if len(numbers) == 0: return "{w[0]}{response}{w[1]}³".format( response=' '.join(args[1:]), w=' ' if findall(r":\w+$", ' '.join(args[1:])) else '()' ) elif len(numbers) > 8: return "Whoa! That's 2 many cubes!" return sub( r"( [0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)", lambda match: " {:g} ".format(float(match.groups()[0]) ** 3), ' ' + ' '.join(args[1:]) + ' ' ) else: return "Usage: !cube [number]"
def get_binary(): logger = logging.getLogger() regex = compile(r'gpg \(GnuPG\) ([1-2])\..*') gpg_subprocess = Popen(['gpg', '--version'], stdout=PIPE, stderr=None) stdout, _ = gpg_subprocess.communicate() version = stdout.decode('utf-8').splitlines()[0] match = regex.match(version) if match: group = match.groups()[0] logger.debug('get_binary: gpg, version: "%s"', group) if group == "2": return 'gpg' if group == "1": gpg2_subprocess = Popen(['gpg2', '--version'], stdout=PIPE, stderr=None) stdout_2, _ = gpg2_subprocess.communicate() version_2 = stdout_2.decode('utf-8').splitlines()[0] m_2 = regex.match(version_2) if m_2: g_2 = m_2.groups()[0] logger.debug('get_binary: gpg2, version: "%s"', g_2) if g_2 == "2": return 'gpg2' logging.getLogger().error('get_binary: unkown gpg version') exit(1)
def _get_label(self): with self.losetup_context_manager() as device: out = file("-s", device, **SH_OPTS).stdout.decode("utf8").strip() # "label:" is for fat partitions, # "volume name" is for ext partitions # "BTRFS Filesystem label" is for btrfs partitions match = search( '(BTRFS Filesystem label|label:|volume name) "(.*)"', out, ) if match is not None: return match.groups()[1].strip()
def parse_session_mode_and_map(log_data): """ Get the mode and map from the log data. Returning a tuple of mode and map of the session. @param log_data: The data from the log file """ try: match = search( r"<\d{2}:\d{2}> [^d]* Loading level \w+\/(\w+), \w+ (\w+)", log_data) line_map, line_mode = match.groups() return (line_mode, line_map) except Exception: print("Something is wrong with the log file!")
def __call__(self, args, data=None, **kwargs): if args[1] == '2' and len(args) == 2: return "8! Whoa, that's 2Cubed!" numbers = findall("( [0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)", ' ' + ' '.join(args[1:]) + ' ') if len(numbers) == 0: return "{w[0]}{response}{w[1]}³".format( response=' '.join(args[1:]), w=' ' if findall(":\w+$", ' '.join(args[1:])) else '()') elif len(numbers) > 8: return "Whoa! That's 2 many cubes!" return sub("( [0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)", lambda match: " {:g} ".format(float(match.groups()[0])**3), ' ' + ' '.join(args[1:]) + ' ')
# This is the base url. To form a url with data, we need to append # a number to it. baseurl = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' # The regular expression that will get the numbers out of the # appropriate text. target = compile('.+ the next nothing is ([0-9]{1,5})') # The initial url appendage nothing = 12345 # Loop forever. We will break out when we reach the end of the linked # steps. while True: # Compose the target url and strip out newline characters that will # confuse our regex engine. urldata = urlopen(baseurl + str(nothing)).read().decode().replace('\n','') match = target.match(urldata) # If there is a regex match, use the new number as nothing and proceed. if match: nothing = match.groups(0)[0] # Avoids a wrench in the works. if 'Divide by two' in urldata: nothing = int(nothing)/2 # If there's not a match to the regular expression, print what the URL # says and break out of the forever loop. elif not match: print(urldata) break
pattern = r"(?P<first>abc)def(ghi)j" m1 = match(pattern, "abcdefghij") if m1: print(m1.group(1)) print(m1.group(2)) print(m1.groups()) print(m1.group()) # # Example as name: import re pattern = r"(?P<first>gol)(?:dys)(ran)" match = re.match(pattern, "goldysran") if match: print(match.group("first")) print(match.groups()) # gol ('gol', 'ran') # # in simple words ?:.... skips the word but numbring remains same as you can see in the the given example(dys) skipped.... # What would be the result of len(match.groups()) of a match of (a)(b(?:c)(d)(?:e))? ---> 3 # Group 1 - (a) # Group 2 - (bd) # Group 3 - (d) # Length of Groups = 3 # The full code would be: import re pattern = r"(a)(b(?:c)(d)(?:e))" match = re.match(pattern, "abcde")
###### 🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶🐱🐶 ###### # Every program needs a version. It uses the common version convention global __version__; __version__ = '.'.join(list(map(str, [528, 0])) + ['491']); # Python has very strict version names so we need to validate it from re import match match = match(r'([0123456790]{1,5})\.([0123456790]{1,5})\.([0123456790]{1,5})', __version__) if match is None: # Our version is very wrong so we need to report it __version__ = "The version is very wrong"; import warnings; warnings.warn(__version__); else: try: __version__ = '{}.{}'.format(int(match.groups()[0], int(match.groups()\ [1]))) __version__ = __version__ + str(int(match.groups()[3])); except: __version__ = 'Error'; __all__ = tuple(['__version__']); ###### 🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲🐺🐲 ######