def extract_purchased(value): try: return int( re.template('purchased in (\d\d\d\d)', flags=re.IGNORECASE).findall(value)[0]) except IndexError: pass
def prepare_query_value(self, *args, **kwargs): value = super(self.__class__, self).prepare_query_value(*args, **kwargs) if isinstance(value, basestring): return value.lower() if isinstance(value, RE_COMPILED_TYPE): return re.template(value.pattern, value.flags | re.IGNORECASE) return value
def collect_curl_data(url, con, head): data = {} try: req = requests.get(url) except Exception: return data match_con = re.findall(re.template(con), str(req.content)) p = subprocess.Popen(["curl", "-ILs", url], stdout=subprocess.PIPE) match_head = re.findall(re.template(head), str(p.communicate()[0])) data.update({ 'content': { 'responce_code': req.status_code, 'contains': match_con }, 'header': { 'header': match_head } }) req.close() return data
def sub(self, haystack, beg, end, needles, escape=None, ignore_case=False): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with *end*, then return the modified string. For example:: >>> yt = Term() >>> yt.sub('spam and eggs', 'x', 'z', ['and']) 'spam xandz eggs' This is particularly useful for emphasizing certain words in output: for example, calling :func:`sub` with *beg* = MODE['bold'] and *end* = MODE['normal'] will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. Note, however, that the :func:`sub_mode`, :func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods provide convenient ways to access this same emphasizing functionality. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :param escape: a function that accepts a string and returns the same string with problematic characters escaped. By default, :func:`re.escape` is used. :param ignore_case: whether case should be ignored when searching for matches :return: *haystack* with *beg* prefixing, and *end* postfixing, occurrences of the strings in *needles* """ if not self.__enabled: return haystack if not escape: escape = re.escape render = lambda match: beg + match.group() + end for needle in needles: pat = escape(needle) if ignore_case: pat = re.template(pat, re.I) haystack = re.sub(pat, render, haystack) return haystack
def sub(self, haystack, beg, end, needles, escape=None, ignore_case=False): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with *end*, then return the modified string. For example:: >>> yt = Term() >>> yt.sub('spam and eggs', 'x', 'z', ['and']) 'spam xandz eggs' This is particularly useful for emphasizing certain words in output: for example, calling :func:`sub` with *beg* = MODE['bold'] and *end* = MODE['normal'] will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. Note, however, that the :func:`sub_mode`, :func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods provide convenient ways to access this same emphasizing functionality. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :param escape: a function that accepts a string and returns the same string with problematic characters escaped. By default, :func:`re.escape` is used. :param ignore_case: whether case should be ignored when searching for matches :return: *haystack* with *beg* prefixing, and *end* postfixing, occurrences of the strings in *needles* """ if not self.__enabled: return haystack if not escape: escape = re.escape render = lambda match: beg + match.group() + end for needle in needles: pat = escape(needle) if ignore_case: pat = re.template(pat, re.I) haystack = re.sub(pat, render, haystack) return haystack
def get_workers(self): data = self._getData('workers') if data and data.get('workers'): counter = 0 workers = data.get('workers') for worker in workers: position, created = Position.objects.get_or_create( name=worker['position']['name']) new_worker = dict(name=worker['name'], surname=worker['surname'], patronymic=worker['patronymic'], rank="1", position=position) for st in self.STATIONS.keys(): pattern = re.template(st) if pattern.search(worker['station']['name']): new_worker['station'] = self.STATIONS[st] instance, created = Worker.objects.get_or_create(**new_worker) if created: counter += 1 print( 'Созданно {0} новых работников, всего в системе {1} работников' .format(counter, Worker.objects.count()))
def check_url_headers_server(url, regex_str_srv): p = subprocess.Popen(["curl", "-ILs", url], stdout=subprocess.PIPE) match = re.findall(re.template(regex_str_srv), str(p.communicate()[0])) print(json.dumps({'header': match}))
def path(self): rstr = "pyShelf/src" r = re.template(rstr) _pathre = re.match("pyShelf/src")
def update_event(self, inp=-1): self.set_output_val(0, re.template(self.input(0), self.input(1)))
from __future__ import absolute_import import mongoengine from flask import request, abort from . import quantum from datetime import datetime, date, time import re RE_COMPILED_TYPE = type(re.template('hello')) class LowerCaseEmailField(mongoengine.EmailField): def to_mongo(self, *args, **kwargs): return super(self.__class__, self).to_mongo(*args, **kwargs).lower() def prepare_query_value(self, *args, **kwargs): value = super(self.__class__, self).prepare_query_value(*args, **kwargs) if isinstance(value, basestring): return value.lower() if isinstance(value, RE_COMPILED_TYPE): return re.template(value.pattern, value.flags | re.IGNORECASE) return value class QuantumField(mongoengine.fields.BaseField): """A Quantum field. Uses the trex.support.quantum library. Stores raw datetimes in mongo (always as UTC) """ def validate(self, value):
def __init__(self): parser = argparse.ArgumentParser( description="osbs test harness mock JSON creator") parser.add_argument( "user", action='store', help="name of user to use for Basic Authentication in OSBS") parser.add_argument("--config", action='store', metavar="PATH", help="path to configuration file", default=DEFAULT_CONFIGURATION_FILE) parser.add_argument( "--instance", "-i", action='store', metavar="SECTION_NAME", help="section within config for requested instance", default="stage") parser.add_argument( "--password", action='store', help="password to use for Basic Authentication in OSBS") parser.add_argument("--mock-dir", metavar="DIR", action="store", default=DEFAULT_DIR, help="mock JSON responses are stored in DIR") parser.add_argument( "--imagestream", metavar="IMAGESTREAM", action="store", default=DEFAULT_IMAGESTREAM_FILE, help="Image name for image stream import. Defaults to " + DEFAULT_IMAGESTREAM_FILE) parser.add_argument( "--image_server", metavar="IMAGESERVER", action="store", default=DEFAULT_IMAGESTREAM_SERVER, help="Server for image stream import. Defaults to " + DEFAULT_IMAGESTREAM_SERVER) parser.add_argument( "--image_tags", metavar="IMAGETAGS", action="store", nargs=3, default=DEFAULT_IMAGESTREAM_TAGS, help="Image stream tags as 3 space separated values.") parser.add_argument("--os-version", metavar="OS_VER", action="store", default=OS_VERSION, help="OpenShift version of the mock JSONs") args = parser.parse_args() self.user = args.user self.password = args.password mock_path = args.mock_dir self.mock_dir = "/".join([mock_path, args.os_version]) find_or_make_dir(self.mock_dir) self.capture_dir = tempfile.mkdtemp() args.git_url = "https://github.com/TomasTomecek/docker-hello-world.git" args.git_branch = "master" args.git_commit = "HEAD" os_conf = Configuration(conf_file=args.config, conf_section=args.instance, cli_args=args) build_conf = Configuration(conf_file=args.config, conf_section=args.instance, cli_args=args) set_logging(level=logging.INFO) self.osbs = OSBS(os_conf, build_conf) setup_json_capture(self.osbs, os_conf, self.capture_dir) self.imagestream_file = args.imagestream self.imagestream_server = args.image_server self.imagestream_tags = args.image_tags self.rh_pattern = re.template("redhat.com") self.ex_pattern = "(\S+\.)*redhat.com" # noqa:W605
# # # # # # # # # # # # # # # # # # # # # # # # # # Removes the header from .csv files # # 1. Search all the file in directory and choose those with .csv extention # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import sys import os import re try: new_path_list = sys.argv[1].split('/') except IndexError: pass # new_path = os.getcwd() else: new_path = os.path.join(new_path_list) os.chdir(new_path) regex_obj = re.template('*.csv')
""" https://leetcode.com/problems/defanging-an-ip-address/ """ address = "255.100.50.0" address = "1.1.1.0" import re check_num = re.findall("\d+", address) check_dots = re.findall("\.", address) if len(check_num) == 4 and len(check_dots) == 3: print(address.replace(".", "[.]")) re.template("255.100.50.0") re.findall("\d+", address) re.search("[0-9].[0-9].[0-9].[0-9]", address)
def validate_build(value): allowed = re.template('[а-я0-9]') for letter in value: if not allowed.findall(letter): raise ValidationError('{} is not allowed build number'.format(value))
def validate_mac(value): allowed = re.template('[\:A-Fa-f0-9]') for letter in value: if not allowed.findall(letter): raise ValidationError('{} is not allowed symbol for MAC'.format(value))
parser.add_argument('-s', '--spattern', help='A Pattern to check each response on and continue if it does not matches', default='') parser.add_argument('--post', help='Use HTTP POST requests') parser.add_argument('--get', help='Use HTTP GET requests') parser.add_argument('--prefix', help='A suffix to add after the parameter value', default='') parser.add_argument('--suffix', help='A prefix to add before the parameter value', default='') parser.add_argument('--length', type=int, help='The length of the randomly generated value', default=6) args = parser.parse_args() url = args.url if str(url).endswith('/'): url = url[:-1] delay = args.delay data = args.data if not data: data = 'username=?' elif str(data).find('?') == -1: if str(data).endswith('?'): data += '&' data += 'username=?' fpatt = re.template(args.fpattern) spatt = re.template(args.spattern) http = HttpManager()
# >>> def rpl(mo): # ... print('called') # ... return ' ' # ... # >>> re.sub('-', rpl, 'I-Am-You-Everything') # called # called # called # 'I Am You Everything' # >>> # >>> def rpl(mo): # ... if mo.group(0) == '-': # ... return ' ' # ... elif mo.group(0) == '\\': # ... return '-' # ... # >>> re.sub(r'-|\\', rpl, 'I-Am-You 2017\\12\\07') # 'I Am You 2017-12-07' # 9、re.subn()和 re.sub()一样,返回值为元组 # 10、re.escape() re.error re.purge() re.template() # 返回的匹配类型对象 Match Objects