Python re.IGNORECASE Examples

The following are 30 code examples of re.IGNORECASE(). 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 also want to check out all available functions/classes of the module re , or try the search function .
Example #1
Source File: magic_check_fn.py    From recipes-py with Apache License 2.0 10 votes vote down vote up
def render_re(regex):
  """Renders a repr()-style value for a compiled regular expression."""
  actual_flags = []
  if regex.flags:
    flags = [
      (re.IGNORECASE, 'IGNORECASE'),
      (re.LOCALE, 'LOCALE'),
      (re.UNICODE, 'UNICODE'),
      (re.MULTILINE, 'MULTILINE'),
      (re.DOTALL, 'DOTALL'),
      (re.VERBOSE, 'VERBOSE'),
    ]
    for val, name in flags:
      if regex.flags & val:
        actual_flags.append(name)
  if actual_flags:
    return 're.compile(%r, %s)' % (regex.pattern, '|'.join(actual_flags))
  else:
    return 're.compile(%r)' % regex.pattern 
Example #2
Source File: __init__.py    From aegea with Apache License 2.0 8 votes vote down vote up
def validate_hostname(hostname):
    if len(hostname) > 255:
        raise Exception("Hostname {} is longer than 255 characters".format(hostname))
    if hostname[-1] == ".":
        hostname = hostname[:-1]
    allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    if not all(allowed.match(x) for x in hostname.split(".")):
        raise Exception("Hostname {} is not RFC 1123 compliant".format(hostname)) 
Example #3
Source File: port_scan.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def regex(self, response, port):
        match = False

        if re.search(b'<title>502 Bad Gateway', response):
            return match

        for pattern in SIGNS:
            pattern = pattern.split(b'|')
            if re.search(pattern[-1], response, re.IGNORECASE):
                text = response.decode('utf-8', 'ignore')
                match = True
                proto = {"server": pattern[1].decode(), "port": port, "banner": text}
                self.out.append(proto)
                break
        if not match:
            proto = {"server": get_server(port), "port": port, "banner": response.decode('utf-8', 'ignore')}
            self.out.append(proto) 
Example #4
Source File: utils.py    From qutebrowser with 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 #5
Source File: utils.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def normalize_release_tags(name, real_title):
    import re
    import xbmc
    def _normalize_name(val):
        proper = re.sub(r"[\[\(\]\)]", "", val)
        proper = re.sub(r"'", "", proper)
        proper = re.sub(r"\W", " ", proper)
        proper = re.sub(r"\s+", " ", proper)
        return proper
    name = _normalize_name(name)
    real_title = _normalize_name(real_title)
    release_tags = re.compile(real_title, re.IGNORECASE).sub("", name)
    tags = map(re.escape, VIDEO_CODECS.keys() + AUDIO_CODECS.keys() + RESOLUTIONS.keys())
    release_tags = re.compile("(%s)" % "|".join(tags), re.IGNORECASE).sub("", release_tags)
    release_tags = re.sub(r"\s+", " ", release_tags)
    return release_tags.strip() 
Example #6
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_process(cmd, args=''):
    fullcmd = '%s %s' % (cmd, args)
    pipeout = popen(fullcmd)
    try:
        firstline = pipeout.readline()
        cmd_not_found = re.search(
            b'(not recognized|No such file|not found)',
            firstline,
            re.IGNORECASE
        )
        if cmd_not_found:
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example #7
Source File: downloads.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def transform_path(path):
    r"""Do platform-specific transformations, like changing E: to E:\.

    Returns None if the path is invalid on the current platform.
    """
    if not utils.is_windows:
        return path
    path = utils.expand_windows_drive(path)
    # Drive dependent working directories are not supported, e.g.
    # E:filename is invalid
    if re.search(r'^[A-Z]:[^\\]', path, re.IGNORECASE):
        return None
    # Paths like COM1, ...
    # See https://github.com/qutebrowser/qutebrowser/issues/82
    if pathlib.Path(path).is_reserved():
        return None
    return path 
Example #8
Source File: drone.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def query_state(self, query):
        """
        Query the drone current state return a dictionary of every drone state
        whose message name contains the query string
        :return: dictionary of drone state
        :param: query, the string to search for in the message received from the drone.
        """
        result = OrderedDict()
        for message in self.messages.values():
            if re.search(query, message.fullName, re.IGNORECASE):
                try:
                    result[message.fullName] = message.state()
                except RuntimeError:
                    continue
            for arg_name in message.args_name:
                name = message.fullName + "." + arg_name
                if re.search(query, name, re.IGNORECASE):
                    try:
                        result[message.fullName] = message.state()
                    except RuntimeError:
                        break
        return result 
Example #9
Source File: pastebin_crawler.py    From pastebin-monitor with GNU General Public License v2.0 6 votes vote down vote up
def check_paste ( self, paste_id ):
        paste_url = self.PASTEBIN_URL + paste_id
        try:
            paste_txt = PyQuery ( url = paste_url )('#paste_code').text()

            for regex,file,directory in self.regexes:
                if re.match ( regex, paste_txt, re.IGNORECASE ):
                    Logger ().log ( 'Found a matching paste: ' + paste_url + ' (' + file + ')', True, 'CYAN' )
                    self.save_result ( paste_url,paste_id,file,directory )
                    return True
            Logger ().log ( 'Not matching paste: ' + paste_url )
        except KeyboardInterrupt:
            raise
        except:
            Logger ().log ( 'Error reading paste (probably a 404 or encoding issue).', True, 'YELLOW')
        return False 
Example #10
Source File: interop.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def check_juniper_rift_in_path():
    if shutil.which("rift-environ") is None:
        fatal_error("Cannot find Juniper RIFT (rift-environ) in PATH")

    # run it and check version
    output = subprocess.check_output(["rift-environ",
                                      "--version"], universal_newlines=True)
    # print (output)
    regex = re.compile(r"^.hrift encoding schema: *(\d+)\.(\d+).*",
                       re.IGNORECASE  | re.MULTILINE)
    major = re.search(regex, output)

    if not major or not major.group(1):
        fatal_error("Cannot detect major version of Juniper RIFT")

    minor = major.group(2)
    major = major.group(1)

    expected_minor = protocol_minor_version
    expected_major = protocol_major_version

    if int(major) != expected_major or int(minor) != expected_minor:
        fatal_error("Wrong Major/Minor version of Juniper RIFT: (expected {}.{}, got {}.{})"
                    .format(expected_major, expected_minor, major, minor)) 
Example #11
Source File: testcase_definition.py    From httpninja with Apache License 2.0 6 votes vote down vote up
def ReqBuilder(self, target_BoxObject):
        filename, extension = os.path.splitext(target_BoxObject.path)
        extension = extension[1:] # removing the dot character before the extension
        result = self.templateRequest.safe_substitute(ip=target_BoxObject.ip,
                                                    port=target_BoxObject.port,
                                                    path=target_BoxObject.path,
                                                    filename=filename,
                                                    extension=extension,
                                                    hostname=target_BoxObject.hostname,
                                                    description=target_BoxObject.description)

        if self.autoContentLength:
            bodylength = len(result) - re.search("(\r\n\r\n)|(\n\n)", result).end()
            if re.search("content\\-length", result, re.IGNORECASE):
                result = re.sub(r"(?i)content\-length:\s*\d+", "Content-Length: " + str(bodylength),
                                result, 1)
            else:
                result = re.sub(r"(\r\n\r\n)|(\n\n)", "\r\nContent-Length: " + str(bodylength) + "\r\n\r\n",
                                result, 1)

        return result 
Example #12
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def set_memlimit(limit):
    global max_memuse
    global real_max_memuse
    sizes = {
        'k': 1024,
        'm': _1M,
        'g': _1G,
        't': 1024*_1G,
    }
    m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
                 re.IGNORECASE | re.VERBOSE)
    if m is None:
        raise ValueError('Invalid memory limit %r' % (limit,))
    memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
    real_max_memuse = memlimit
    if memlimit > MAX_Py_ssize_t:
        memlimit = MAX_Py_ssize_t
    if memlimit < _2G - 1:
        raise ValueError('Memory limit %r too low to be useful' % (limit,))
    max_memuse = memlimit 
Example #13
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, pairs, reflections={}):
        """
        Initialize the chatbot.  Pairs is a list of patterns and responses.  Each
        pattern is a regular expression matching the user's statement or question,
        e.g. r'I like (.*)'.  For each such pattern a list of possible responses
        is given, e.g. ['Why do you like %1', 'Did you ever dislike %1'].  Material
        which is matched by parenthesized sections of the patterns (e.g. .*) is mapped to
        the numbered positions in the responses, e.g. %1.

        :type pairs: list of tuple
        :param pairs: The patterns and responses
        :type reflections: dict
        :param reflections: A mapping between first and second person expressions
        :rtype: None
        """

        self._pairs = [(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs]
        self._reflections = reflections
        self._regex = self._compile_reflections() 
Example #14
Source File: pwnpass.py    From password_pwncheck with MIT License 6 votes vote down vote up
def test(self,user,password,token):
        for line in self.regexs:
            (ignore,regex) = line
            regex = regex.replace('<user>',user)
            results = None
            if ignore == True:
                results = re.search(regex,password,re.IGNORECASE)
            else:
                results = re.search(regex,password)
            if results != None:
                if self.debug:
                    print(" \- - A blacklisted term was found")
                return (20,None)
        if self.debug:
            print(" \- * No blacklisted terms were found")
        return (0,None) 
Example #15
Source File: __init__.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, pairs, reflections={}):
        """
        Initialize the chatbot.  Pairs is a list of patterns and responses.  Each
        pattern is a regular expression matching the user's statement or question,
        e.g. r'I like (.*)'.  For each such pattern a list of possible responses
        is given, e.g. ['Why do you like %1', 'Did you ever dislike %1'].  Material
        which is matched by parenthesized sections of the patterns (e.g. .*) is mapped to
        the numbered positions in the responses, e.g. %1.

        @type pairs: C{list} of C{tuple}
        @param pairs: The patterns and responses
        @type reflections: C{dict}
        @param reflections: A mapping between first and second person expressions
        @rtype: C{None}
        """

        self._pairs = [(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs]
        self._reflections = reflections

    # bug: only permits single word expressions to be mapped 
Example #16
Source File: support.py    From jawfish with MIT License 6 votes vote down vote up
def set_memlimit(limit):
    global max_memuse
    global real_max_memuse
    sizes = {
        'k': 1024,
        'm': _1M,
        'g': _1G,
        't': 1024*_1G,
    }
    m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
                 re.IGNORECASE | re.VERBOSE)
    if m is None:
        raise ValueError('Invalid memory limit %r' % (limit,))
    memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
    real_max_memuse = memlimit
    if memlimit > MAX_Py_ssize_t:
        memlimit = MAX_Py_ssize_t
    if memlimit < _2G - 1:
        raise ValueError('Memory limit %r too low to be useful' % (limit,))
    max_memuse = memlimit 
Example #17
Source File: mysql.py    From django-migration-linter with Apache License 2.0 5 votes vote down vote up
def detect_column(sql):
        if isinstance(sql, str):
            regex_result = re.search("COLUMN [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1)
            regex_result = re.search("MODIFY [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1) 
Example #18
Source File: base.py    From django-migration-linter with Apache License 2.0 5 votes vote down vote up
def detect_column(sql):
        if isinstance(sql, str):
            regex_result = re.search("COLUMN [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1) 
Example #19
Source File: base.py    From django-migration-linter with Apache License 2.0 5 votes vote down vote up
def detect_table(sql):
        if isinstance(sql, str):
            regex_result = re.search("TABLE [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1) 
Example #20
Source File: mixins.py    From pykaldi with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """ Sets up the inference for classname so that getImpl constructs the correct object """
        self._test_replacer = re.compile(re.escape("test"), re.IGNORECASE)
        self.classname = self.getClassname()
        self.filename = '/tmp/temp.ark'
        self.rspecifier = 'ark,t:{}'.format(self.filename) 
Example #21
Source File: utils.py    From MnemonicReader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def regex_match_score(prediction, pattern):
    """Check if the prediction matches the given regular expression."""
    try:
        compiled = re.compile(
            pattern,
            flags=re.IGNORECASE + re.UNICODE + re.MULTILINE
        )
    except BaseException:
        logger.warn('Regular expression failed to compile: %s' % pattern)
        return False
    return compiled.match(prediction) is not None 
Example #22
Source File: workflow.py    From gist-alfred with MIT License 5 votes vote down vote up
def _search_for_query(self, query):
        if query in self._search_pattern_cache:
            return self._search_pattern_cache[query]

        # Build pattern: include all characters
        pattern = []
        for c in query:
            # pattern.append('[^{0}]*{0}'.format(re.escape(c)))
            pattern.append('.*?{0}'.format(re.escape(c)))
        pattern = ''.join(pattern)
        search = re.compile(pattern, re.IGNORECASE).search

        self._search_pattern_cache[query] = search
        return search 
Example #23
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _compile_reflections(self):
        sorted_refl = sorted(self._reflections.keys(), key=len,
                reverse=True)
        return  re.compile(r"\b({0})\b".format("|".join(map(re.escape,
            sorted_refl))), re.IGNORECASE) 
Example #24
Source File: completiondelegate.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def highlightBlock(self, text):
        """Override highlightBlock for custom highlighting."""
        for match in re.finditer(self._pattern, text, re.IGNORECASE):
            start, end = match.span()
            length = end - start
            self.setFormat(start, length, self._format) 
Example #25
Source File: singular.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def singular(word, custom={}):

    if word in custom.keys():
		return custom[word]

	# Recursion of compound words (e.g. mothers-in-law). 
    if "-" in word:
        words = word.split("-")
        if len(words) > 1 and words[1] in plural_prepositions:
	        return singular(words[0], custom)+"-"+"-".join(words[1:])

    lower_cased_word = word.lower()
    for w in singular_uninflected:
        if w.endswith(lower_cased_word):
            return word
    for w in singular_uncountable:
        if w.endswith(lower_cased_word):
            return word
    for w in singular_ie:
        if lower_cased_word.endswith(w+"s"):
            return w

    for w in singular_irregular.keys():
        match = re.search('('+w+')$',word, re.IGNORECASE)
        if match:
            return re.sub(
                '(?i)'+w+'$', 
                singular_irregular[w], word)

    for rule in range(len(singular_rules)):
        match = re.search(singular_rules[rule][0], word, re.IGNORECASE)
        if match:
            groups = match.groups()
            for k in range(0,len(groups)):
                if groups[k] == None:
                    singular_rules[rule][1] = singular_rules[rule][1].replace('\\'+str(k+1), '')
            return re.sub(
                singular_rules[rule][0], 
                singular_rules[rule][1], word)

    return word 
Example #26
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get(self, getme=None, fromEnd=False):
        if not getme:
            return self
        try:
            getme = int(getme)
            if getme < 0:
                return self[:(-1 * getme)]
            else:
                return [self[getme-1]]
        except IndexError:
            return []
        except ValueError:
            rangeResult = self.rangePattern.search(getme)
            if rangeResult:
                start = rangeResult.group('start') or None
                end = rangeResult.group('start') or None
                if start:
                    start = int(start) - 1
                if end:
                    end = int(end)
                return self[start:end]

            getme = getme.strip()

            if getme.startswith(r'/') and getme.endswith(r'/'):
                finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)
                def isin(hi):
                    return finder.search(hi)
            else:
                def isin(hi):
                    return (getme.lower() in hi.lowercase)
            return [itm for itm in self if isin(itm)] 
Example #27
Source File: cyber.py    From cyberdisc-bot with MIT License 5 votes vote down vote up
def __init__(self, bot: Bot):
        self.bot = bot

        self.matches = [
            (re.compile(i[0], re.IGNORECASE), i[1]) for i in self.match_strings
        ] 
Example #28
Source File: autocomplete_entry.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, autocompleteList, *args, **kwargs):
 
        # Listbox length
        if 'listboxLength' in kwargs:
            self.listboxLength = kwargs['listboxLength']
            del kwargs['listboxLength']
        else:
            self.listboxLength = 4
 
        # Custom matches function
        if 'matchesFunction' in kwargs:
            self.matchesFunction = kwargs['matchesFunction']
            del kwargs['matchesFunction']
        else:
            def matches(fieldValue, acListEntry):
                pattern = re.compile('.*' + re.escape(fieldValue) + '.*', re.IGNORECASE)
                return re.match(pattern, str(acListEntry))
                
            self.matchesFunction = matches
        
        Entry.__init__(self, *args, **kwargs)
        self.focus()
 
        self.autocompleteList = autocompleteList
        
        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()
 
        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.moveUp)
        self.bind("<Down>", self.moveDown)
        self.bind("<Return>", self.selection)
        
        self.listboxUp = False 
Example #29
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def search(self, target):
        target = target.strip()
        if target[0] == target[-1] == '/' and len(target) > 1:
            target = target[1:-1]
        else:
            target = re.escape(target)
        pattern = re.compile(target, re.IGNORECASE)
        return [s for s in self if pattern.search(s)] 
Example #30
Source File: zelka.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 5 votes vote down vote up
def do_login():
  r = s.post('%s/takelogin.php' % BASE_URL, data={'username' : plugin.get_setting('z_usr'), 'password' : plugin.get_setting('z_pass')}, headers = HEADERS)
  if re.search(plugin.get_setting('z_usr'), r.text, re.IGNORECASE):
    return True