Python re.IGNORECASE Examples

The following are 30 code examples for showing how to use re.IGNORECASE(). 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: recipes-py   Author: luci   File: magic_check_fn.py    License: Apache License 2.0 9 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
Project: aegea   Author: kislyuk   File: __init__.py    License: Apache License 2.0 7 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
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: 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 4
Project: pastebin-monitor   Author: fabiospampinato   File: pastebin_crawler.py    License: 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 5
Project: httpninja   Author: irsdl   File: testcase_definition.py    License: 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 6
Project: password_pwncheck   Author: CboeSecurity   File: pwnpass.py    License: 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 7
Project: jawfish   Author: war-and-code   File: support.py    License: 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 8
Project: Vxscan   Author: al0ne   File: port_scan.py    License: 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 9
Project: razzy-spinner   Author: rafasashi   File: __init__.py    License: 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 10
Project: razzy-spinner   Author: rafasashi   File: util.py    License: 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 11
Project: verge3d-blender-addon   Author: Soft8Soft   File: support.py    License: 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 12
Project: rift-python   Author: brunorijsman   File: interop.py    License: 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 13
Project: plugin.video.kmediatorrent   Author: jmarth   File: utils.py    License: 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 14
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 15
Project: qutebrowser   Author: qutebrowser   File: downloads.py    License: 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 16
Project: olympe   Author: Parrot-Developers   File: drone.py    License: 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 17
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    License: 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 18
Project: cyberdisc-bot   Author: CyberDiscovery   File: admin.py    License: MIT License 5 votes vote down vote up
def check_bad_name(nick):
    for i in NICKNAME_PATTERNS:
        if re.match(i, nick, re.IGNORECASE):
            return True
    return False 
Example 19
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: 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 20
Project: cherrypy   Author: cherrypy   File: modfastcgi.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_process(cmd, args=''):
    pipein, pipeout = os.popen4('%s %s' % (cmd, args))
    try:
        firstline = pipeout.readline()
        if (re.search(r'(not recognized|No such file|not found)', firstline,
                      re.IGNORECASE)):
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example 21
Project: cherrypy   Author: cherrypy   File: modfcgid.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_process(cmd, args=''):
    pipein, pipeout = os.popen4('%s %s' % (cmd, args))
    try:
        firstline = pipeout.readline()
        if (re.search(r'(not recognized|No such file|not found)', firstline,
                      re.IGNORECASE)):
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example 22
Project: cherrypy   Author: cherrypy   File: modwsgi.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_process(cmd, args=''):
    pipein, pipeout = os.popen4('%s %s' % (cmd, args))
    try:
        firstline = pipeout.readline()
        if (re.search(r'(not recognized|No such file|not found)', firstline,
                      re.IGNORECASE)):
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example 23
Project: cherrypy   Author: cherrypy   File: modpy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_process(cmd, args=''):
    pipein, pipeout = os.popen4('%s %s' % (cmd, args))
    try:
        firstline = pipeout.readline()
        if (re.search(r'(not recognized|No such file|not found)', firstline,
                      re.IGNORECASE)):
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example 24
Project: kw_condition   Author: coreanq   File: main.py    License: MIT License 5 votes vote down vote up
def waitingTradeSystemStateEntered(self):
        # 장시작 전에 조건이 시작하도록 함 
        self.sigSelectCondition.emit()       

        # 반환값 : 조건인덱스1^조건명1;조건인덱스2^조건명2;…;
        # result = '조건인덱스1^조건명1;조건인덱스2^조건명2;'
        result = self.getConditionNameList()
        searchPattern = r'(?P<index>[^\/:*?"<>|;]+)\^(?P<name>[^\/:*?"<>|;]+);'
        fileSearchObj = re.compile(searchPattern, re.IGNORECASE)
        findList = fileSearchObj.findall(result)
        
        tempDict = dict(findList)
        print(tempDict)
        

        condition_name_screenNo_dict = {}
        for number, condition in tempDict.items():
            condition_name_screenNo_dict[condition] = [kw_util.sendConditionScreenNo + '{}'.format(int (number)), number]
        
        start_info = []
        start_name = None

        for name, info in condition_name_screenNo_dict.items():

            if name == self.current_condition_name:
                start_info = info
                start_name = name
            else: 
                print("stop condition " + name + ", screen_no: " + info[0] + ", nIndex " + '{}'.format(int(info[1]) ) )
                self.sendConditionStop( info[0], name, int(info[1])  )
                pass

        print("start condition " + start_name + ", screen_no: " + start_info[0] + ", nIndex " + '{}'.format(int(start_info[1])) )
        self.sendCondition( start_info[0], start_name, int(start_info[1]) , 1) 

        pass 
Example 25
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    License: Apache License 2.0 5 votes vote down vote up
def is_date(word):
  if (not (bool(re.search("[a-z0-9]", word, re.IGNORECASE)))):
    return False
  if (len(word) != 10):
    return False
  if (word[4] != "-"):
    return False
  if (word[7] != "-"):
    return False
  for i in range(len(word)):
    if (not (word[i] == "X" or word[i] == "x" or word[i] == "-" or re.search(
        "[0-9]", word[i]))):
      return False
  return True 
Example 26
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    License: Apache License 2.0 5 votes vote down vote up
def is_money(self, word):
    if (not (bool(re.search("[a-z0-9]", word, re.IGNORECASE)))):
      return False
    for i in range(len(word)):
      if (not (word[i] == "E" or word[i] == "." or re.search("[0-9]",
                                                             word[i]))):
        return False
    return True 
Example 27
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    License: Apache License 2.0 5 votes vote down vote up
def pre_process_sentence(self, tokens, ner_tags, ner_values):
    sentence = []
    tokens = tokens.split("|")
    ner_tags = ner_tags.split("|")
    ner_values = ner_values.split("|")
    ner_tags, ner_values = self.remove_consecutive(ner_tags, ner_values)
    #print "old: ", tokens
    for i in range(len(tokens)):
      word = tokens[i]
      if (ner_values[i] != "" and
          (ner_tags[i] == "NUMBER" or ner_tags[i] == "MONEY" or
           ner_tags[i] == "PERCENT" or ner_tags[i] == "DATE")):
        word = ner_values[i]
        word = word.replace(">", "").replace("<", "").replace("=", "").replace(
            "%", "").replace("~", "").replace("$", "").replace("£", "").replace(
                "€", "")
        if (re.search("[A-Z]", word) and not (is_date(word)) and not (
            self.is_money(word))):
          word = tokens[i]
        if (is_number(ner_values[i])):
          word = float(ner_values[i])
        elif (is_number(word)):
          word = float(word)
        if (tokens[i] == "score"):
          word = "score"
      if (is_number(word)):
        word = float(word)
      if (not (self.annotated_word_reject.has_key(word))):
        if (is_number(word) or is_date(word) or self.is_money(word)):
          sentence.append(word)
        else:
          word = full_normalize(word)
          if (not (self.annotated_word_reject.has_key(word)) and
              bool(re.search("[a-z0-9]", word, re.IGNORECASE))):
            m = re.search(",", word)
            sentence.append(word.replace(",", ""))
    if (len(sentence) == 0):
      sentence.append("UNK")
    return sentence 
Example 28
Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def mailto(self):
        """
        Returns the email recipients of this note
        Don't use validate_email because addresses may also be in
        Name <email> format (replies to emails)
        """
        to = []
        recipients = [r.strip() for r in self.recipient.split(',')]
        for r in recipients:
            m = re.search(r'([\w\.\-_]+@[\w\.\-_]+)', r, re.IGNORECASE)
            if m:
                to.append(m.group(0))

        return ','.join(to) 
Example 29
Project: post--memorization-in-rnns   Author: distillpub   File: export-checkpoint.py    License: MIT License 5 votes vote down vote up
def make_filename(self, name):
        name = name.replace('/', '_')
        name = re.sub("[^A-Z0-9_]", "", name, flags=re.IGNORECASE)
        return name 
Example 30
Project: ANGRYsearch   Author: DoTheEvo   File: angrysearch.py    License: GNU General Public License v2.0 5 votes vote down vote up
def regexp(expr, item):
    name = item.split('/')[-1]
    r = re.compile(expr, re.IGNORECASE)
    return r.search(name) is not None