当前位置: 首页>>代码示例>>Python>>正文


Python re.search函数代码示例

本文整理汇总了Python中re.search函数的典型用法代码示例。如果您正苦于以下问题:Python search函数的具体用法?Python search怎么用?Python search使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了search函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: indent_code

    def indent_code(self, code):
        """Accepts a string of code or a list of code lines"""

        # code mostly copied from ccode
        if isinstance(code, string_types):
            code_lines = self.indent_code(code.splitlines(True))
            return "".join(code_lines)

        tab = "  "
        inc_regex = ("^function ", "^if ", "^elseif ", "^else$", "^for ")
        dec_regex = ("^end$", "^elseif ", "^else$")

        # pre-strip left-space from the code
        code = [line.lstrip(" \t") for line in code]

        increase = [int(any([search(re, line) for re in inc_regex])) for line in code]
        decrease = [int(any([search(re, line) for re in dec_regex])) for line in code]

        pretty = []
        level = 0
        for n, line in enumerate(code):
            if line == "" or line == "\n":
                pretty.append(line)
                continue
            level -= decrease[n]
            pretty.append("%s%s" % (tab * level, line))
            level += increase[n]
        return pretty
开发者ID:brajeshvit,项目名称:virtual,代码行数:28,代码来源:octave.py

示例2: check_date_format

        def check_date_format(date):
            """
            Checks to see whether dates are in proper datetime format and converts times in ##/##/#### format to
            datetime or raises an error when it encounters a different format
            """
            # check if date is already in the proper format
            datetime_pattern = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$")

            # regex and its accompanying strptime format
            misc_date_formats = (
                (re.compile(r"\d{2}/\d{2}/\d{4}\+\d{2}:\d{2}T\d{2}:\d{2}:\d{2}$"), "%m/%d/%Y+%H:%MT%H:%M:%S"),
                (re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$"), "%Y-%m-%dT%H:%M:%S"),
                (re.compile(r"\d{4}/\d{2}/\d{2}$"), "%d/%m/%YT%H:%M:%S"),
                (re.compile(r"\d{4}/\d{2}/\d{2}$"), "%/%d/%YT%H:%M:%S"),
                (re.compile(r"\d{2}/\d{2}/\d{4}\+\d{2}:\d{2}$"), "%m/%d/%Y+%H:%M"),
                (re.compile(r"\d{4}-\d{2}-\d{2}$"), "%Y-%m-%d"),
                (re.compile(r"\d{2}/\d{2}/\d{4}$"), "%d/%m/%Y"),
                (re.compile(r"\d{2}/\d{2}/\d{4}$"), "%m/%d/%Y"),
            )

            matched = re.search(datetime_pattern, date)
            if matched:
                return date
            else:
                for date_format_tuple in misc_date_formats:
                    matched = re.search(date_format_tuple[0], date)
                    if matched:
                        try:
                            timestruct = time.strptime(date, date_format_tuple[1])
                            timedatetime = datetime.datetime.fromtimestamp(time.mktime(timestruct))
                            return timedatetime.strftime("%Y-%m-%dT%H:%M:%S")
                        except ValueError:
                            continue
                else:
                    raise TypeError("unknown date format given: %s" % date)
开发者ID:hibozzy,项目名称:mediatum,代码行数:35,代码来源:sitemap.py

示例3: loadAccountInfo

    def loadAccountInfo(self, user, req):
        validuntil = None
        trafficleft = None
        premium = None

        html = req.load("http://uploading.com/")

        premium = re.search(self.PREMIUM_PATTERN, html) is None

        m = re.search(self.VALID_UNTIL_PATTERN, html)
        if m:
            expiredate = m.group(1).strip()
            self.logDebug("Expire date: " + expiredate)

            try:
                validuntil = time.mktime(time.strptime(expiredate, "%b %d, %Y"))

            except Exception, e:
                self.logError(e)

            else:
                if validuntil > time.mktime(time.gmtime()):
                    premium = True
                else:
                    premium = False
                    validuntil = None
开发者ID:toroettg,项目名称:pyload,代码行数:26,代码来源:UploadingCom.py

示例4: clean_up

 def clean_up(self):
     """ Move DQ outputs to their appropriate directory """
     try:
         data_dir = os.environ["DATA"]
         plots_dir = os.environ["PLOTS"]
         logs_dir = os.environ["LOGS"]
     except KeyError as detail:
         print "GenerateSpectrum.clean_up: error", detail, "not set"
         print " --> source analysis environment scripts before running!"
         sys.exit(1)
     for root, dirs, files in os.walk(os.getcwd()):
         for file in files:
             is_data = re.search(r".*\.root$", file)
             is_plot = re.search(r".*\.png$", file)
             hostname = socket.gethostname()
             is_log =  re.search(r"^rat\."+hostname+r"\.[0-9]+\.log$", file)
             if is_data:
                 try:
                     root_file = TFile(file)
                     tree = root_file.Get("T")
                     tree.ls()
                 except ReferenceError as detail:
                     "generate_spectrum.clean_up: error in TFile,", detail
                     sys.exit(1)
                 file_manips.copy_file(os.path.join(root, file), data_dir)
             elif is_plot:
                 file_manips.copy_file(os.path.join(root, file), plots_dir)
             elif is_log:
                 file_manips.copy_file(os.path.join(root, file), logs_dir)
开发者ID:ashleyrback,项目名称:MajoRat,代码行数:29,代码来源:generate_spectrum.py

示例5: resolve_resources

def resolve_resources(br, path):
    lecture = []
    b_video = []
    video   = []
    pdf     = []
    pptx    = []

    for l in br.links():
        m_video = re.search(r'https:[\S]+download.mp4[\S]+\'', str(l))
        m_pdf = re.search(r'https*:[\S]+/([\S]+\.pdf)', str(l))
        m_pptx = re.search(r'https*:[\S]+/([\S]+\.pptx*)', str(l))
    
        if m_video:
            b_video.append(m_video.group().rstrip("'"))
        if m_pdf:
            pdf.append([resolve_name_with_hex(m_pdf.group(1)), m_pdf.group()])
        if m_pptx:
            pptx.append([resolve_name_with_hex(m_pptx.group(1)), m_pptx.group()])

    for l in b_video:
        br.open(l)
        tmp_l = br.geturl()
        index = tmp_l.find('?')
        tmp_l = tmp_l[ : index]
        video.append(tmp_l)
        index = tmp_l.rfind('/')
        lecture.append(resolve_name_with_hex(tmp_l[index+1 :]))

    if len(lecture) == len(video):
        mp4 = zip(lecture, video)
    else:
        print 'Video names resolving error. Ignore videos...'
        mp4 = []
    return mp4, pdf, pptx
开发者ID:lorenzosantos,项目名称:Coursera.org-Downloader,代码行数:34,代码来源:coursera_downloader.py

示例6: initialize_constants

def initialize_constants():
    global __version__, __appname__, modules, functions, basenames, scripts

    src = open('src/calibre/constants.py', 'rb').read()
    nv = re.search(r'numeric_version\s+=\s+\((\d+), (\d+), (\d+)\)', src)
    __version__ = '%s.%s.%s'%(nv.group(1), nv.group(2), nv.group(3))
    __appname__ = re.search(r'__appname__\s+=\s+(u{0,1})[\'"]([^\'"]+)[\'"]',
            src).group(2)
    epsrc = re.compile(r'entry_points = (\{.*?\})', re.DOTALL).\
            search(open('src/calibre/linux.py', 'rb').read()).group(1)
    entry_points = eval(epsrc, {'__appname__': __appname__})

    def e2b(ep):
        return re.search(r'\s*(.*?)\s*=', ep).group(1).strip()

    def e2s(ep, base='src'):
        return (base+os.path.sep+re.search(r'.*=\s*(.*?):', ep).group(1).replace('.', '/')+'.py').strip()

    def e2m(ep):
        return re.search(r'.*=\s*(.*?)\s*:', ep).group(1).strip()

    def e2f(ep):
        return ep[ep.rindex(':')+1:].strip()

    basenames, functions, modules, scripts = {}, {}, {}, {}
    for x in ('console', 'gui'):
        y = x + '_scripts'
        basenames[x] = list(map(e2b, entry_points[y]))
        functions[x] = list(map(e2f, entry_points[y]))
        modules[x] = list(map(e2m, entry_points[y]))
        scripts[x] = list(map(e2s, entry_points[y]))
开发者ID:AEliu,项目名称:calibre,代码行数:31,代码来源:__init__.py

示例7: _apache_index

  def _apache_index(self, url):
    r = requests.get(url)
    if r.status_code != 200:
      raise ValueError(url+" status:"+str(r.status_code))
    r.dirs = []
    r.files = []
    for l in r.content.split("\n"):
      # '<img src="/icons/folder.png" alt="[DIR]" /> <a href="7.0/">7.0/</a>       03-Dec-2014 19:57    -   '
      # ''<img src="/icons/tgz.png" alt="[   ]" /> <a href="owncloud_7.0.4-2.diff.gz">owncloud_7.0.4-2.diff.gz</a>                     09-Dec-2014 16:53  9.7K   <a href="owncloud_7.0.4-2.diff.gz.mirrorlist">Details</a>'
      # 
      m = re.search("<a\s+href=[\"']?([^>]+?)[\"']?>([^<]+?)[\"']?</a>\s*([^<]*)", l, re.I)
      if m:
	# ('owncloud_7.0.4-2.diff.gz', 'owncloud_7.0.4-2.diff.gz', '09-Dec-2014 16:53  9.7K   ')
	m1,m2,m3 = m.groups()

	if re.match("(/|\?|\w+://)", m1):	# skip absolute urls, query strings and foreign urls
	  continue
	if re.match("\.?\./?$", m1):	# skip . and ..
	  continue

	m3 = re.sub("[\s-]+$", "", m3)
	if re.search("/$", m1):
	  r.dirs.append([m1, m3])
	else:
	  r.files.append([m1, m3])
    return r
开发者ID:4213,项目名称:administration,代码行数:26,代码来源:ListUrl.py

示例8: create_movie_tiles_content

def create_movie_tiles_content(movies):
    '''Generates a string with the movie tile markup.'''
    # The HTML content for this section of the page
    content = ''
    for movie in movies:
        # Extract the youtube ID from the url
        youtube_id_match = re.search(
            r'(?<=v=)[^&#]+',
            movie.trailer_youtube_url
        )
        youtube_id_match = youtube_id_match or re.search(
            r'(?<=be/)[^&#]+',
            movie.trailer_youtube_url
        )
        trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None

        # Append the tile for the movie with its content filled in
        content += MOVIE_TILE_CONTENT.format(
            movie_id=movie.movie_id,
            movie_title=movie.title,
            poster_image_url=movie.poster_image_url,
            trailer_youtube_id=trailer_youtube_id,
            actors=create_actor_list_content(movie.actors),
            year=movie.year,
            synopsis=movie.synopsis
        )

    return content
开发者ID:skawaguchi,项目名称:udacity-full-stack-project-1,代码行数:28,代码来源:fresh_tomatoes.py

示例9: parser

def parser(content, option, outfp):
    score = 0
    for lines in re.findall(
                    "=+LINUX\s+DATA\s+BELOW\s*=+\n(.*?)\n\*\s+Trademarks",
                    content,
                    re.DOTALL):
        if lines:
            line_list = lines.splitlines()
            for i in range(0, len(line_list)):
                if re.search("MEMORY\s+INDEX", line_list[i]):
                    memory_line = line_list[i]
                elif re.search("INTEGER\s+INDEX", line_list[i]):
                    int_line = line_list[i]
                else:
                    if re.search("FLOATING-POINT", line_list[i]):
                        float_line = line_list[i]
            if option == "int":
                line_list.remove(memory_line)
                line_list.remove(float_line)
                score = int_line.split(":")[1].strip()
            elif option == "float":
                line_list.remove(int_line)
                line_list.remove(memory_line)
                score = float_line.split(":")[1].strip()
            else:
                if option == "memory":
                    line_list.remove(int_line)
                    line_list.remove(float_line)
                    score = memory_line.split(":")[1].strip()

            for i in range(0, len(line_list)):
                outfp.write(line_list[i] + '\n')
            return score
开发者ID:open-estuary,项目名称:caliper,代码行数:33,代码来源:nbench_parser.py

示例10: get_status

    def get_status(self):
        self.zd_up = 0
        self.zd_pid = 0
        self.zd_should_be_up = 0
        self.zd_status = None
        resp = self.send_action("status")
        if not resp:
            return resp
        m = re.search("(?m)^application=(\d+)$", resp)
        if not m:
            return resp
        self.zd_up = 1
        self.zd_pid = int(m.group(1))
        self.zd_status = resp
        m = re.search("(?m)^should_be_up=(\d+)$", resp)
        if m:
            self.zd_should_be_up = int(m.group(1))
        else:
            self.zd_should_be_up = 1
        m = re.search("(?m)^testing=(\d+)$", resp)
        if m:
            self.zd_testing = int(m.group(1))
        else:
            self.zd_testing = 0

        return resp
开发者ID:Petchesi-Iulian,项目名称:Crawler,代码行数:26,代码来源:zdctl.py

示例11: do_changes

    def do_changes(self, resource):
        changes = self.list_changes(resource)
        changed = False

        if "state" in changes and changes["state"][0] != changes["state"][1]:
            action = "start"
            if changes["state"][1] == "stopped":
                action = "stop"

            # start or stop the service
            result = self._io.run("/sbin/service",
                            [resource.name, action])

            if re.search("^Failed", result[1]):
                raise Exception("Unable to %s %s: %s" % (action, resource.name, result[1]))

            changed = True

        if "enabled" in changes and changes["enabled"][0] != changes["enabled"][1]:
            action = "on"

            if changes["enabled"][1] == False:
                action = "off"

            result = self._io.run("/sbin/chkconfig", [resource.name, action])
            changed = True

            if re.search("^Failed", result[1]):
                raise Exception("Unable to %s %s: %s" % (action, resource.name, result[1]))

        return changed
开发者ID:hdeweirdt,项目名称:imp-std,代码行数:31,代码来源:resources.py

示例12: parse_contact

def parse_contact(raw):
    contact_details = {'name': '', 'email': ''}
    links = []

    match_mail = re.search(contact_mail_pattern, raw)
    match_url = re.search(contact_url_pattern, raw)
    match_intern = re.search(contact_intern_pattern, raw)

    if match_mail:
        if re.match(mail_address_pattern, match_mail.group('email')):
            # found an email address
            contact_details = {'name': match_mail.group('name'),
                               'email': match_mail.group('email')}
        else:
            contact_details = {'name': match_mail.group('name'),
                               'email': ''}
    elif match_url:
        # found a hyperlink
        links.append({'ref': 'contact', 'href': match_url.group('url')})
    elif match_intern:
        # found a link to the wiki page '/contact'
        contact_details = {'name': ' / '.join(name for name in match_intern.groupdict().values() if (name is not None)), 'email': ''}
    else:
        name = raw.replace("[", "").replace("]", "").replace("|", "").strip()
        if name:
            # found a name
            contact_details = {'name': name, 'email': ''}
        else:
            # found nothing
            pass
    return contact_details, links
开发者ID:kerel-fs,项目名称:ogn-rdb,代码行数:31,代码来源:wikidotparser.py

示例13: GenVerilog

 def GenVerilog(self,fp,config):
   for bodyextension in ('_Rx.v','_Tx.v',):
     body = self.LoadCore(self.peripheralFile,bodyextension);
     if hasattr(self,'RTR') or hasattr(self,'RTRn'):
       body = re.sub(r'@[email protected]\n','',body);
       body = re.sub(r'@[email protected]\n','',body);
     else:
       if re.search(r'@[email protected]',body):
         body = re.sub(r'@[email protected]*[email protected][email protected]\n','',body,flags=re.DOTALL);
     for subpair in (
         ( r'@[email protected]',    self.RTR if hasattr(self,'RTR') else self.RTRn if hasattr(self,'RTRn') else '', ),
         ( r'@[email protected]',    '' if hasattr(self,'RTR') else '!', ),
         ( r'\bL__',           '[email protected]@__',          ),
         ( r'\bgen__',         '[email protected]@__',        ),
         ( r'\bs__',           '[email protected]@__',          ),
         ( r'@[email protected]',        self.insignal,          ),
         ( r'@[email protected]',    str(self.baudmethod),   ),
         ( r'@[email protected]',          str(self.sync),         ),
         ( r'@[email protected]',      str(self.deglitch),     ),
         ( r'@[email protected]',        str(self.inFIFO),       ),
         ( r'@[email protected]',       self.CTS if hasattr(self,'CTS') else ('!%s' % self.CTSn) if hasattr(self,'CTSn') else '1\'b1', ),
         ( r'@[email protected]',         str(self.nStop),        ),
         ( r'@[email protected]',       str(self.outFIFO),      ),
         ( r'@[email protected]',          self.namestring,        ),
       ):
       if re.search(subpair[0],body):
         body = re.sub(subpair[0],subpair[1],body);
     body = self.GenVerilogFinal(config,body);
     fp.write(body);
开发者ID:freecores,项目名称:ssbcc,代码行数:29,代码来源:UART.py

示例14: get_mediaid

 def get_mediaid(self):
     match = re.search(r"mediaId = '([^']+)';", self.get_urldata())
     if not match:
         match = re.search(r'media-id="([^"]+)"', self.get_urldata())
     if not match:
         match = re.search(r'screen9-mid="([^"]+)"', self.get_urldata())
     if not match:
         match = re.search(r'data-id="([^"]+)"', self.get_urldata())
     if not match:
         match = re.search(r'data-id=([^ ]+) ', self.get_urldata())
     if not match:
         match = re.search(r'data-videoid="([^"]+)"', self.get_urldata())
     if not match:
         match = re.search('s.src="(https://csp-ssl.picsearch.com[^"]+|http://csp.picsearch.com/rest[^"]+)', self.get_urldata())
         if match:
             data = self.http.request("get", match.group(1))
             match = re.search(r'mediaid": "([^"]+)"', data.text)
         if not match:
             match = re.search('iframe src="(//csp.screen9.com[^"]+)"', self.get_urldata())
             if match:
                 url = "http:{0}".format(match.group(1))
                 data = self.http.request("get", url)
                 match = re.search(r"mediaid: '([^']+)'", data.text)
     if not match:
         urlp = urlparse(self.url)
         match = urlp.fragment
     return match
开发者ID:spaam,项目名称:svtplay-dl,代码行数:27,代码来源:picsearch.py

示例15: parse_changelog

def parse_changelog():
    with open('CHANGES') as f:
        lineiter = iter(f)
        for line in lineiter:
            match = re.search('^Version\s+(.*)', line.strip())

            if match is None:
                continue

            version = match.group(1).strip()

            if lineiter.next().count('-') != len(line.strip()):
                fail('Invalid hyphen count below version line: %s', line.strip())

            while 1:
                released = lineiter.next().strip()
                if released:
                    break

            match = re.search(r'Released (\w+\s+\d+\w+\s+\d+)', released)

            if match is None:
                fail('Could not find release date in version %s' % version)

            datestr = parse_date(match.group(1).strip())

            return version, datestr
开发者ID:fc-thrisp-hurrata-dlm-graveyard,项目名称:flask-anyform,代码行数:27,代码来源:release.py


注:本文中的re.search函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。