Python re.fullmatch() Examples

The following are 30 code examples for showing how to use re.fullmatch(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module re , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def expand_windows_drive(path: str) -> str:
    r"""Expand a drive-path like E: into E:\.

    Does nothing for other paths.

    Args:
        path: The path to expand.
    """
    # Usually, "E:" on Windows refers to the current working directory on drive
    # E:\. The correct way to specifify drive E: is "E:\", but most users
    # probably don't use the "multiple working directories" feature and expect
    # "E:" and "E:\" to be equal.
    if re.fullmatch(r'[A-Z]:', path, re.IGNORECASE):
        return path + "\\"
    else:
        return path 
Example 2
Project: qutebrowser   Author: qutebrowser   File: docutils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _parse_arg_inside(self, line: str) -> bool:
        """Parse subsequent argument lines."""
        argname = self._cur_arg_name
        assert argname is not None

        descs = self.arg_descs[argname]
        assert isinstance(descs, list)

        if re.fullmatch(r'[A-Z][a-z]+:', line):
            if not descs[-1].strip():
                del descs[-1]
                return True
        elif not line.strip():
            descs.append('\n\n')
        elif line[4:].startswith(' '):
            descs.append(line.strip() + '\n')
        else:
            self._process_arg(line)
        return False 
Example 3
Project: qutebrowser   Author: qutebrowser   File: configtypes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
        self._basic_py_validation(value, str)
        if isinstance(value, usertypes.Unset):
            return value
        elif not value:
            return None

        self._validate_encoding(value)
        self._validate_valid_values(value)

        if self.forbidden is not None and any(c in value
                                              for c in self.forbidden):
            raise configexc.ValidationError(value, "may not contain the chars "
                                            "'{}'".format(self.forbidden))
        if self.minlen is not None and len(value) < self.minlen:
            raise configexc.ValidationError(value, "must be at least {} chars "
                                            "long!".format(self.minlen))
        if self.maxlen is not None and len(value) > self.maxlen:
            raise configexc.ValidationError(value, "must be at most {} chars "
                                            "long!".format(self.maxlen))
        if self.regex is not None and not re.fullmatch(self.regex, value):
            raise configexc.ValidationError(value, "does not match {}"
                                            .format(self.regex))

        return value 
Example 4
Project: qutebrowser   Author: qutebrowser   File: configtypes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
        self._basic_py_validation(value, str)
        if isinstance(value, usertypes.Unset):
            return value
        elif not value:
            return None

        if not self.font_regex.fullmatch(value):  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")

        if (value.endswith(' default_family') and
                self.default_family is not None):
            value = value.replace('default_family', self.default_family)

        if 'default_size ' in value and self.default_size is not None:
            value = value.replace('default_size', self.default_size)

        return value 
Example 5
Project: qutebrowser   Author: qutebrowser   File: configtypes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
        self._basic_py_validation(value, str)
        if isinstance(value, usertypes.Unset):
            return value
        elif not value:
            return None

        match = self.font_regex.fullmatch(value)
        if not match:  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")
        for group in 'style', 'weight', 'namedweight', 'size':
            if match.group(group):
                raise configexc.ValidationError(value, "may not include a "
                                                "{}!".format(group))

        return value 
Example 6
Project: thingsboard-gateway   Author: thingsboard   File: request_connector.py    License: Apache License 2.0 6 votes vote down vote up
def on_attributes_update(self, content):
        try:
            for attribute_request in self.__attribute_updates:
                if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
                    converted_data = attribute_request["converter"].convert(attribute_request, content)
                    response_queue = Queue(1)
                    request_dict = {"config": {**attribute_request,
                                               **converted_data},
                                    "request": request}
                    attribute_update_request_thread = Thread(target=self.__send_request,
                                                             args=(request_dict, response_queue, log),
                                                             daemon=True,
                                                             name="Attribute request to %s" % (converted_data["url"]))
                    attribute_update_request_thread.start()
                    attribute_update_request_thread.join()
                    if not response_queue.empty():
                        response = response_queue.get_nowait()
                        log.debug(response)
                    del response_queue
        except Exception as e:
            log.exception(e) 
Example 7
Project: thingsboard-gateway   Author: thingsboard   File: request_connector.py    License: Apache License 2.0 6 votes vote down vote up
def server_side_rpc_handler(self, content):
        try:
            for rpc_request in self.__rpc_requests:
                if fullmatch(rpc_request["deviceNameFilter"], content["device"]) and fullmatch(rpc_request["methodFilter"], content["data"]["method"]):
                    converted_data = rpc_request["converter"].convert(rpc_request, content)
                    response_queue = Queue(1)
                    request_dict = {"config": {**rpc_request,
                                               **converted_data},
                                    "request": request}
                    request_dict["config"].get("uplink_converter")
                    rpc_request_thread = Thread(target=self.__send_request,
                                                args=(request_dict, response_queue, log),
                                                daemon=True,
                                                name="RPC request to %s" % (converted_data["url"]))
                    rpc_request_thread.start()
                    rpc_request_thread.join()
                    if not response_queue.empty():
                        response = response_queue.get_nowait()
                        log.debug(response)
                        self.__gateway.send_rpc_reply(device=content["device"], req_id=content["data"]["id"], content=response[2])
                    self.__gateway.send_rpc_reply(success_sent=True)

                    del response_queue
        except Exception as e:
            log.exception(e) 
Example 8
Project: thingsboard-gateway   Author: thingsboard   File: opcua_uplink_converter.py    License: Apache License 2.0 6 votes vote down vote up
def convert(self, config, data):
        device_name = self.__config["deviceName"]
        result = {"deviceName": device_name,
                  "deviceType": self.__config.get("deviceType", "OPC-UA Device"),
                  "attributes": [],
                  "telemetry": [], }
        try:
            information_types = {"attributes": "attributes", "timeseries": "telemetry"}
            for information_type in information_types:
                for information in self.__config[information_type]:
                    path = TBUtility.get_value(information["path"], get_tag=True)
                    if isinstance(config, tuple):
                        config_information = config[0].replace('\\\\', '\\') if path == config[0].replace('\\\\', '\\') or fullmatch(path, config[0].replace('\\\\', '\\')) else config[1].replace('\\\\', '\\')
                    else:
                        config_information = config.replace('\\\\', '\\')
                    if path == config_information or fullmatch(path, config_information) or path.replace('\\\\', '\\') == config_information:
                        result[information_types[information_type]].append({information["key"]: information["path"].replace("${"+path+"}", str(data))})
            return result
        except Exception as e:
            log.exception(e) 
Example 9
Project: thingsboard-gateway   Author: thingsboard   File: rest_connector.py    License: Apache License 2.0 6 votes vote down vote up
def on_attributes_update(self, content):
        try:
            for attribute_request in self.__attribute_updates:
                if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and \
                        fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
                    converted_data = attribute_request["downlink_converter"].convert(attribute_request, content)
                    response_queue = Queue(1)
                    request_dict = {"config": {**attribute_request,
                                               **converted_data},
                                    "request": regular_request}
                    with self._app.test_request_context():
                        attribute_update_request_thread = Thread(target=self.__send_request,
                                                                 args=(request_dict, response_queue, log),
                                                                 daemon=True,
                                                                 name="Attribute request to %s" % (converted_data["url"]))
                        attribute_update_request_thread.start()
                        attribute_update_request_thread.join()
                    if not response_queue.empty():
                        response = response_queue.get_nowait()
                        log.debug(response)
                    del response_queue
        except Exception as e:
            log.exception(e) 
Example 10
Project: nsf   Author: bayesiains   File: autils.py    License: MIT License 6 votes vote down vote up
def started_event(self, ex_info, command, host_info, start_time, config, meta_info, _id):
        prefix = config['dataset']

        if config['run_descr']:
            prefix += '-' + config['run_descr']

        def existing_run_nrs():
            pattern = '{}(-\d+)?'.format(prefix)
            run_dirs = (d for d in os.listdir(self.basedir)
                        if os.path.isdir(os.path.join(self.basedir, d)))
            for run_dir in run_dirs:
                match = re.fullmatch(pattern, run_dir)
                if match:
                    num_str = match.group(1)
                    yield int(num_str[1:] if num_str else 0)

        max_nr = max(existing_run_nrs(), default=None)
        if max_nr is None:
            return prefix
        else:
            return prefix + '-{}'.format(max_nr + 1) 
Example 11
Project: ibllib   Author: int-brain-lab   File: spikeglx.py    License: MIT License 6 votes vote down vote up
def read_meta_data(md_file):
    """
    Reads the spkike glx metadata file and parse in a dictionary
    Agnostic: does not make any assumption on the keys/content, it just parses key=values

    :param md_file: last sample to be read, python slice-wise
    :return: Data array, sync trace, meta-data
    """
    with open(md_file) as fid:
        md = fid.read()
    d = {}
    for a in md.splitlines():
        k, v = a.split('=')
        # if all numbers, try to interpret the string
        if v and re.fullmatch('[0-9,.]*', v) and v.count('.') < 2:
            v = [float(val) for val in v.split(',')]
            # scalars should not be nested
            if len(v) == 1:
                v = v[0]
        # tildes in keynames removed
        d[k.replace('~', '')] = v
    d['neuropixelVersion'] = _get_neuropixel_version_from_meta(d)
    d['serial'] = _get_serial_number_from_meta(d)
    return Bunch(d) 
Example 12
Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: emoji.py    License: GNU General Public License v3.0 6 votes vote down vote up
def replace_emoji(text: str, client: Client) -> str:
    if text is None:
        return ''
    output = text
    symbols = re.findall(r'\{([A-Z0-9/]{1,3})\}', text)
    for symbol in symbols:
        name = symbol
        name = name.replace('/', '')
        if len(name) == 1:
            if re.fullmatch('[0-9]', name):
                name = '0' + name
            else:
                name = name + name
        emoji = find_emoji(name, client)
        if emoji is not None:
            output = output.replace('{' + symbol + '}', str(emoji))
    return output 
Example 13
Project: typhon   Author: atmtools   File: dataset.py    License: MIT License 6 votes vote down vote up
def get_info_for_granule(self, p):
        """Return dict (re.fullmatch) for granule, based on re

        Arguments:
            
            p (pathlib.Path): path to granule

        Returns:
            
            dict: dictionary with info, such as returned by
            :func:`re.fullmatch`.
        """

        if not isinstance(p, pathlib.Path):
            p = pathlib.Path(p)
        m = self._re.fullmatch(p.name)
        return m.groupdict() 
Example 14
Project: py-uio   Author: mvduin   File: device.py    License: MIT License 6 votes vote down vote up
def from_sysfs( cls, uio, info, parent=None ):
        index = int( re.fullmatch( r'map([0-9])', info.name ).group(1) )

        def getinfo( attr ):
            with (info/attr).open() as f:
                return f.readline().rstrip()

        # If no name has been supplied, the region gets an auto-generated name
        # containing the full DT path.  These are useless, ignore them.
        name = getinfo( 'name' )
        if name == '' or name[0] == '/':
            name = None

        # get memory region bounds
        address = int( getinfo('addr'), 0 )
        size = int( getinfo('size'), 0 )

        return MemRegion( parent, address, size, name, uio, index ) 
Example 15
Project: sacred   Author: IDSIA   File: gcs_observer.py    License: MIT License 6 votes vote down vote up
def _is_valid_bucket(bucket_name: str):
    """Validates correctness of bucket naming.

    Reference: https://cloud.google.com/storage/docs/naming
    """
    if bucket_name.startswith("gs://"):
        return False

    if len(bucket_name) < 3 or len(bucket_name) > 63:
        return False

    # IP address
    if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", bucket_name):
        return False

    if not re.fullmatch(r"([^A-Z]|-|_|[.]|)+", bucket_name):
        return False

    if ".." in bucket_name:
        return False

    if "goog" in bucket_name or "g00g" in bucket_name:
        return False

    return True 
Example 16
Project: TheCannon   Author: annayqho   File: simpletable.py    License: MIT License 6 votes vote down vote up
def get(self, v, full_match=False):
        """ returns a table from columns given as v

        this function is equivalent to :func:`__getitem__` but preserve the
        Table format and associated properties (units, description, header)

        Parameters
        ----------
        v: str
            pattern to filter the keys with

        full_match: bool
            if set, use :func:`re.fullmatch` instead of :func:`re.match`

        """
        new_keys = self.keys(v)
        t = self.__class__(self[new_keys])
        t.header.update(**self.header)
        t._aliases.update((k, v) for (k, v) in self._aliases.items() if v in new_keys)
        t._units.update((k, v) for (k, v) in self._units.items() if v in new_keys)
        t._desc.update((k, v) for (k, v) in self._desc.items() if v in new_keys)
        return t 
Example 17
Project: gpu-utils   Author: Ricks-Lab   File: GPUmodule.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_valid_pstate_list_str(self, ps_str: str, clk_name: str) -> bool:
        """
        Check if the given p-states are valid for the given clock.

        :param ps_str: String of comma separated pstate numbers
        :param clk_name: The target clock name
        :return: True if valid
        """
        if ps_str == '':
            return True
        if not re.fullmatch(PATTERNS['VALID_PS_STR'], ps_str):
            return False
        ps_list = self.prm.mclk_mask.split(',') if clk_name == 'MCLK' else self.prm.sclk_mask.split(',')
        for ps_val in ps_str.split():
            if ps_val not in ps_list:
                return False
        return True 
Example 18
Project: gpu-utils   Author: Ricks-Lab   File: GPUmodule.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_plot_data(self) -> dict:
        """
        Return a dictionary of dynamic gpu parameters used by gpu-plot to populate a df.

        :return: Dictionary of GPU state info for plot data.
        """
        gpu_state = {'Time': str(self.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT)),
                     'Card#': int(self.prm.card_num)}

        for table_item in self.table_parameters:
            gpu_state_str = str(re.sub(PATTERNS['MHz'], '', str(self.get_params_value(table_item)))).strip()
            if gpu_state_str == 'nan':
                gpu_state[table_item] = np_nan
            elif gpu_state_str.isnumeric():
                gpu_state[table_item] = int(gpu_state_str)
            elif re.fullmatch(PATTERNS['IS_FLOAT'], gpu_state_str):
                gpu_state[table_item] = float(gpu_state_str)
            elif gpu_state_str == '' or gpu_state_str == '-1' or gpu_state_str == 'NA' or gpu_state_str is None:
                gpu_state[table_item] = 'NA'
            else:
                gpu_state[table_item] = gpu_state_str
        return gpu_state 
Example 19
Project: gpu-utils   Author: Ricks-Lab   File: env.py    License: GNU General Public License v3.0 6 votes vote down vote up
def read_amd_driver_version_debian(self) -> bool:
        """
        Read the AMD driver version and store in GutConst object.

        :return: True if successful
        """
        for pkgname in ['amdgpu', 'amdgpu-core', 'amdgpu-pro', 'rocm-utils']:
            try:
                dpkg_out = subprocess.check_output(shlex.split('{} -l {}'.format(self.cmd_dpkg, pkgname)),
                                                   shell=False, stderr=subprocess.DEVNULL).decode().split('\n')
            except (subprocess.CalledProcessError, OSError):
                continue
            for dpkg_line in dpkg_out:
                for driverpkg in ['amdgpu', 'rocm']:
                    if re.search(driverpkg, dpkg_line):
                        LOGGER.debug(dpkg_line)
                        dpkg_items = dpkg_line.split()
                        if len(dpkg_items) > 2:
                            if re.fullmatch(r'.*none.*', dpkg_items[2]): continue
                            print('AMD: {} version: {}'.format(driverpkg, dpkg_items[2]))
                            return True
        print('amdgpu/rocm version: UNKNOWN')
        return False 
Example 20
Project: dash-masternode-tool   Author: Bertrand256   File: app_config.py    License: MIT License 6 votes vote down vote up
def set_rpc_encryption_pubkey(self, key: str):
        """
        AES public key for additional RPC encryption, dedicated for calls transmitting sensitive information
        like protx. Accepted formats: PEM, DER.
        """
        try:
            if key:
                # validate public key by deserializing it
                if re.fullmatch(r'^([0-9a-fA-F]{2})+$', key):
                    serialization.load_der_public_key(bytes.fromhex(key), backend=default_backend())
                else:
                    pubkey = serialization.load_pem_public_key(key.encode('ascii'), backend=default_backend())
                    raw = pubkey.public_bytes(serialization.Encoding.DER,
                                              format=serialization.PublicFormat.SubjectPublicKeyInfo)
                    key = raw.hex()

            if self.__rpc_encryption_pubkey_object and (self.__rpc_encryption_pubkey_der != key or not key):
                self.__rpc_encryption_pubkey_der = None

            self.__rpc_encryption_pubkey_der = key
        except Exception as e:
            logging.exception('Exception occurred')
            raise 
Example 21
Project: Turku-neural-parser-pipeline   Author: TurkuNLP   File: lemma_cache_mod.py    License: Apache License 2.0 5 votes vote down vote up
def is_url_or_email(self, word):
        if re.match(url_regex, word):
            return True
        if re.fullmatch(email_regex, word):
            return True
        return False 
Example 22
Project: friendly-telegram   Author: friendly-telegram   File: initial_setup.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def finish_login(self, request):
        if not self.clients:
            return web.Response(status=400)
        text = await request.text()
        if text:
            if not re.fullmatch(r"[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}", text):
                return web.Response(status=400)
            self.heroku_api_token = text
        else:
            self.heroku_api_token = None
        self._secret_to_uid.update(self._pending_secret_to_uid)
        self.clients_set.set()
        return web.Response() 
Example 23
Project: udapi-python   Author: udapi   File: complywithtext.py    License: GNU General Public License v3.0 5 votes vote down vote up
def allow_space(form):
        """Is space allowed within this token form?"""
        return re.fullmatch('[0-9 ]+([,.][0-9]+)?', form) 
Example 24
Project: ZhihuVAPI   Author: cheezone   File: zhihu.py    License: MIT License 5 votes vote down vote up
def test(object, test_type, value):
    '''
    用于测试属性
    '''
    if value.__class__.__name__ != 'str':
        return False
    if test_type == 'id':
        if object.type_name == '用户':
            return bool(re.fullmatch(r'[\da-zA-Z]{32}', value))
        elif object.type_name == '问题':
            # 19550224 开始
            return bool(re.fullmatch(r'\d{8,12}', value))
        elif object.type_name == '答案':
            return bool(re.fullmatch(r'\d{8,12}', value))
        elif object.type_name == 'Live':
            return bool(re.fullmatch(r'\d{18}', value))
        elif object.type_name == '文章':
            return bool(re.fullmatch(r'\d{8,12}', value))
        elif object.type_name == '专栏':
            return bool(re.fullmatch(r'[\da-zA-Z-_]{1,}', value))
        elif object.type_name == '想法':
            return bool(re.fullmatch(r'[\d]{1,}', value))
    elif test_type == 'token':
        if object.type_name == '用户':
            return bool(re.fullmatch(r'[\da-zA-Z-_]{1,}', value))

    return False 
Example 25
Project: qutebrowser   Author: qutebrowser   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pattern_match(*, pattern, value):
    """Do fnmatch.fnmatchcase like matching, but only with * active.

    Return:
        True on a match, False otherwise.
    """
    re_pattern = '.*'.join(re.escape(part) for part in pattern.split('*'))
    return re.fullmatch(re_pattern, value, flags=re.DOTALL) is not None 
Example 26
Project: qutebrowser   Author: qutebrowser   File: test_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_cmdline_without_argument(self, caplog, config_stub):
        executable = shlex.quote(sys.executable)
        cmdline = '{} -c pass'.format(executable)
        utils.open_file('/foo/bar', cmdline)
        result = caplog.messages[0]
        assert re.fullmatch(
            r'Opening /foo/bar with \[.*python.*/foo/bar.*\]', result) 
Example 27
Project: qutebrowser   Author: qutebrowser   File: test_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_cmdline_with_argument(self, caplog, config_stub):
        executable = shlex.quote(sys.executable)
        cmdline = '{} -c pass {{}} raboof'.format(executable)
        utils.open_file('/foo/bar', cmdline)
        result = caplog.messages[0]
        assert re.fullmatch(
            r"Opening /foo/bar with \[.*python.*/foo/bar.*'raboof'\]", result) 
Example 28
Project: qutebrowser   Author: qutebrowser   File: test_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_setting_override(self, caplog, config_stub):
        executable = shlex.quote(sys.executable)
        cmdline = '{} -c pass'.format(executable)
        config_stub.val.downloads.open_dispatcher = cmdline
        utils.open_file('/foo/bar')
        result = caplog.messages[1]
        assert re.fullmatch(
            r"Opening /foo/bar with \[.*python.*/foo/bar.*\]", result) 
Example 29
Project: qutebrowser   Author: qutebrowser   File: test_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_system_default_application(self, caplog, config_stub,
                                        openurl_mock):
        utils.open_file('/foo/bar')
        result = caplog.messages[0]
        assert re.fullmatch(
            r"Opening /foo/bar with the system application", result)
        openurl_mock.assert_called_with(QUrl('file:///foo/bar')) 
Example 30
Project: qutebrowser   Author: qutebrowser   File: test_checkpyver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_patched_no_errwindow(capfd, monkeypatch):
    """Test with a patched sys.hexversion and --no-err-windows."""
    monkeypatch.setattr(checkpyver.sys, 'argv',
                        [sys.argv[0], '--no-err-windows'])
    monkeypatch.setattr(checkpyver.sys, 'hexversion', 0x03040000)
    monkeypatch.setattr(checkpyver.sys, 'exit', lambda status: None)
    checkpyver.check_python_version()

    stdout, stderr = capfd.readouterr()
    stderr = stderr.rstrip()
    assert not stdout
    assert re.fullmatch(TEXT, stderr), stderr