def parse_request(r): request = ure.compile("[\r\n]").split(r)[0] urllist = ure.compile('\s').split(request) if len(urllist) > 1: url = urllist[1] else: url = '/test' cmdlist = url.split("/") controller = 'test' state = 0 delay = 0 if len(cmdlist) == 4: [n, controller, state, delay] = cmdlist if len(cmdlist) == 3: [n, controller, state] = cmdlist if len(cmdlist) == 2: [n, controller] = cmdlist return [controller, state, delay]
def get_player_id(self, player_name): """ Retrieve the player's ID as defined by LMS. Most likely this is the player's MAC address. """ player_count = 0 player_id = None # Retrieve player count. player_count = int(self.sb_query('player count')) # Retrieve the complete players information. players = ure.compile(r' playerindex%3A[0-9]+ ').split( self.sb_command(self.sock_queries, 'players 0 {}', player_count)) # The first item will be the command we just sent. players.pop(0) # Prepare lookup expression. player_name_regex = ure.compile('name%s%s ' % (r'%3A', urlencode.quote(player_name))) for player in players: if player_name_regex.search(player): player_id = urlencode.unquote( ure.match(r'playerid%3A([^ ]+) ', player).group(1)) break return player_id
def create_server(config): light_controller = controller.create_light_controller( config['light-controller']) router = middleware.create_router([ ('GET', '/v1/light/ping', routes.create_ping_handler(light_controller)), ('POST', '/v1/light/led', routes.create_led_handler(light_controller)), ('GET', ure.compile(r'^/v1/light/pins/(\d+)$'), routes.create_get_pin_handler(light_controller)), ('POST', ure.compile(r'^/v1/light/pins/(\d+)$'), routes.create_set_pin_handler(light_controller)), ('GET', '/v1/light/addresses', routes.create_get_addresses_handler( config['addresses']['file-path'])), ]) default_handler = middleware.not_found(None) server = uhttp.HTTPServer( handler=middleware.use( default_handler, middleware.trace, middleware.recover, router, ), port=config['server']['port'], ) return server
def web_serv(s): html = """<!DOCTYPE html> <html> <head> <title>ESP32 Pins</title> </head> <body> <h1>ESP32 Pins</h1> <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table> </body> <h3>Pick a Color:</h3> <div style="margin:auto;width:236px;"> </html> """ regex = ure.compile('\(') regex2 = ure.compile('\)') regex3 = ure.compile('led') cl, addr = s.accept() log.info('{} : client connected from: {}'.format(timeout(), addr)) cl_file = cl.makefile('rwb', 0) while True: line = cl_file.readline() log.debug('{} : {}'.format(timeout(), line)) if regex3.search(line): out1 = regex.split(line) log.debug('{} : {}'.format(timeout(), out1)) lightraw = regex2.split(out1[1])[0] lightcmd = Convert(lightraw) if not line or line == b'\r\n': break #response = html % '\n'.join(rows) cl.send(line) cl.close() return lightcmd
def read_forecast(): """Read the weather forecast.""" watcher.feed() start_regex = ure.compile(r'timeseries') continue_regex = ure.compile(r'\},\{') hour_regex = ure.compile(r'next_1_hours') precip_regex = ure.compile(r'precipitation_amount\":(\d+\.\d)') date_regex = ure.compile(r'time\":\"(\d+-\d+-\d+)T') # Large chunk size more performant as less regex's run. Must be less than # characters in one timeseries element in the response. chunkSize = 1000 windowSize = chunkSize * 2 rain_today_mm, rain_tomorrow_mm = (0.0, 0.0) window = memoryview(bytearray(windowSize)) emptyChunk = bytes(chunkSize) periodFound, hourFound, precipFound, dateFound = False, False, False, False File.logger().info('%s - Req to: %s', clock.timestamp(), _FORECAST_URL) with requests.get(_FORECAST_URL, headers=secrets.HEADER) as response: File.logger().info('%s - HTTP status: %d', clock.timestamp(), response.status_code) if response.status_code == 200 or response.status_code == 203: for chunk in response.iter_content(chunkSize): # Populate response window window[0:chunkSize] = window[chunkSize:windowSize] if len(chunk) == chunkSize: window[chunkSize:windowSize] = chunk else: # last chunk is short window[chunkSize:windowSize] = emptyChunk window[chunkSize:chunkSize + len(chunk)] = chunk # print(window) windowBytes = bytes(window) # regex requires bytes # Gather precipitation data if continue_regex.search(windowBytes) or\ start_regex.search(windowBytes): periodFound = True if periodFound and hour_regex.search(windowBytes): hourFound = True if periodFound and not dateFound: if (dateGroup := date_regex.search(windowBytes)): dateFound = True date = dateGroup.group(1).decode() if hourFound and not precipFound: if (precipGroup := precip_regex.search(windowBytes)): precipFound = True mm = float(precipGroup.group(1)) if dateFound and precipFound: periodFound, hourFound = False, False dateFound, precipFound = False, False # print(date, mm) if clock.greater_than_tommorow(date): break elif clock.equal_to_today(date): rain_today_mm += mm else: rain_tomorrow_mm += mm
def extract(self, _startStr, _endStr): # we prepare an array to store results = [] # prepare regex to reduces spaces to on space # and remove cr/linefeeds removeWhiteSpaces = ure.compile("( )+") removeCR = ure.compile("[\r\n]") endOfStream = False _startStrBytes = bytes(_startStr, 'utf-8') _endStrBytes = bytes(_endStr, 'utf-8') # start with mininum length of the search String # if it is smaller than the start - end pageStreamBytes = self.raw.read(len(_startStr)) if len(pageStreamBytes) < len(_startStr): endOfStream = True # we must convert the searchstring to bytes als not for all charcters uft-8 encoding is working # like in Curacao (special c) while not endOfStream: if pageStreamBytes == _startStrBytes: # we found a matching string # print('Start found %s ' % pageStreamBytes.decode('utf-8')) # we need to find the end endOfTag = False read = self.raw.read(len(_endStr)) if len(read) == 0: endOfStream = True pageStreamBytes += read while ((not endOfStream) and (not endOfTag)): # comparing the string with the find method is easier # than comparing the bytes if (pageStreamBytes.decode('utf-8')).find(_endStr) > 0: endOfTag = True result = removeWhiteSpaces.sub( '', pageStreamBytes.decode('utf-8')) result = removeCR.sub('', result) results.append(result) # print('Result: %s' % result) else: # read and Append read = self.raw.read(1) if len(read) == 0: endOfStream = True else: pageStreamBytes += read # print('End not Found %s' % pageStreamBytes.decode('utf-8')) else: # we did not find a matching string # and reduce by one character before we add the next # print('not found %s' % pageStream) pageStreamBytes = pageStreamBytes[1:len(_startStrBytes)] read = self.raw.read(1) if len(read) == 0: endOfStream = True pageStreamBytes = pageStreamBytes + read self.close() return results
def prepare_events_regexes(self): """ Prepare regular expressions used for events parsing. The server connection must be already open. """ player_id = urlencode.quote(self.player_id) self.power_regex = ure.compile('{} power ([10])'.format(player_id)) self.volume_regex = ure.compile( '{} mixer volume ([0-9]+)'.format(player_id))
def get_signal_strength(self): csq_at = self.lte.send_at_cmd("AT+CSQ") csq_line_regex = ure.compile("\n") csq_line = csq_line_regex.split(csq_at) csq_string_regex = ure.compile(" ") csq_string = csq_string_regex.split(csq_line[1]) csq_comma = csq_string[1] csq_num_regex = ure.compile(",") csq_num = csq_num_regex.split(csq_comma) csq = csq_num[0] return csq
def parse_bracket_definition(self, language, loaded_modules): """ Parse the bracket defintion """ names = [] subnames = [] find_regex = [] sub_find_regex = [] for params in self.bracket_rules: if is_valid_definition(params, language): try: bh_plugin.load_modules(params, loaded_modules) entry = BracketDefinition(params) if not self.check_compare and entry.compare is not None: self.check_compare = True if not self.check_validate and entry.validate is not None: self.check_validate = True if not self.check_post_match and entry.post_match is not None: self.check_post_match = True self.brackets.append(entry) if not entry.find_in_sub_search_only: find_regex.append(params["open"]) find_regex.append(params["close"]) names.append(params["name"]) else: find_regex.append(r"([^\s\S])") find_regex.append(r"([^\s\S])") if entry.find_in_sub_search: sub_find_regex.append(params["open"]) sub_find_regex.append(params["close"]) subnames.append(params["name"]) else: sub_find_regex.append(r"([^\s\S])") sub_find_regex.append(r"([^\s\S])") except Exception as e: log(e) if len(self.brackets): self.brackets = tuple(self.brackets) debug( "Bracket Pattern: (%s)\n" % ','.join(names) + " (Opening|Closing): (?:%s)\n" % '|'.join(find_regex) ) debug( "SubBracket Pattern: (%s)\n" % ','.join(subnames) + " (Opening|Closing): (?:%s)\n" % '|'.join(sub_find_regex) ) self.sub_pattern = ure.compile("(?:%s)" % '|'.join(sub_find_regex), ure.MULTILINE | ure.IGNORECASE) self.pattern = ure.compile("(?:%s)" % '|'.join(find_regex), ure.MULTILINE | ure.IGNORECASE)
def getNetVar(varName): urlStr = "https://ubicomp.net/sw/db1/var2db.php?varName=" + str(varName) # print(urlStr) # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test3&varValue=14") # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test222&varValue=valTest222") resStr = http_get(urlStr) # import re # standrad python #_, retVar0 = ure.split('\r\n\r\n|\n\n',resStr) # retVar = ure.split(' |\n|\r',retVar0) reg1 = ure.compile('\r\n\r\n|\n\n') reg2 = ure.compile(' |\n|\r') _, retVar0 = reg1.split(resStr) retVar = reg2.split(retVar0) return retVar[0]
def test_re_routes(self): req = MockReq() next_called = False def next_mw(w, r): nonlocal next_called next_called = True calls = [] def users_create_handler(w, req, match): nonlocal calls calls.append(('users_create_handler', match.group(1))) def user_transactions_handler(w, req, match): nonlocal calls calls.append( ('user_transactions_handler', match.group(1), match.group(2))) router = middleware.create_router([ ('GET', ure.compile(r"/v1/users/([A-Za-z0-9\-]+)/create"), users_create_handler), ('GET', ure.compile( r"/v1/users/([A-Za-z0-9\-]+)/transactions/([A-Za-z0-9\-]+)"), user_transactions_handler), ])(next_mw) user1 = str(uuid4()) req.uri = "/v1/users/%s/create" % user1 router(None, req) self.assertEqual(calls, [("users_create_handler", user1)]) self.assertEqual(next_called, False) calls = [] trx1 = str(uuid4()) req.uri = "/v1/users/%s/transactions/%s" % (user1, trx1) router(None, req) self.assertEqual(calls, [("user_transactions_handler", user1, trx1)]) self.assertEqual(next_called, False) calls = [] trx1 = str(uuid4()) req.uri = "/v1/users/%s/update" % (user1) router(None, req) self.assertEqual(calls, []) self.assertEqual(next_called, True) calls = []
def __init__(self, bracket): """ Setup the bracket object by reading the passed in dictionary. """ self.style = bracket.get("style", "default") self.open = ure.compile("\\A" + bracket.get("open", "."), ure.MULTILINE | ure.IGNORECASE) self.close = ure.compile(bracket.get("close", ".") + "\\Z", ure.MULTILINE | ure.IGNORECASE) self.name = bracket["name"] sub_search = bracket.get("sub_bracket_search", "false") self.sub_search_only = sub_search == "only" self.sub_search = self.sub_search_only == True or sub_search == "true" self.compare = bracket.get("compare") self.post_match = bracket.get("post_match") self.scopes = bracket["scopes"]
def read_shortcuts(cls, filename): """Read all shortcuts from given file.""" line_re = ure.compile(r'^\s*(\d+)\s+([^;]*);(.*)$') shortcut_dict = {} input_file = open(filename, 'r') for line in input_file: # Skip empty or comment lines. line = line.strip() if not line or line[0] == '#': continue match = line_re.match(line) if not match: raise BadShortcut("Bad shortcut line: " + line) switch_num = int(match.group(1)) event_groups = tuple( EventGroup(event_group_str.strip()) for event_group_str in match.group(2).split()) label = match.group(3).strip() # Append the Shortcut to the list of shortcuts for this switch. shortcut_dict.setdefault(switch_num, []).append(Shortcut(event_groups, label)) return shortcut_dict
def __init__(self, address, port, debug=-1): # debug values: # -1 disable all logging # 0 (False) normal logging: requests and errors # 1 (True) debug logging # 2 extra debug logging self.debug = debug logging.basicConfig(level=logging.DEBUG) self.address = address self.port = port self.ROUTES = [ # You can specify exact URI string matches... ("/", self.index), ("/ncsi.txt", self.ncsi), # microsoft ("/connecttest.txt", self.connecttest), # microsoft ("/redirect", self.redirect), # microsoft ("/gen_204", self.redirect), # android ("/generate_204", self.redirect), # android ("/hotspot-detect.html", self.redirect), # apple ("/squares", self.squares), ("/file", lambda req, resp: (yield from self.app.sendfile(resp, "captiveportal.py"))), # ... or match using a regex, the match result available as req.url_match # for match group extraction in your view. (re.compile("^/iam/(.+)"), self.hello), ] self.app = picoweb.WebApp("__main__", routes=self.ROUTES)
def find(target, path='/', filter='^.*\.py$', recurse=False, output=''): # create list of files file_list = list(os.ilistdir(path)) # only recurse through the dirs if needed if recurse: for f in file_list: if f[1] == 16384: find(target, merge(path, f[0]), filter, recurse, output) r = ure.compile(filter) # scan the files for f in file_list: if f[1] == 32768: if filter == '' or r.match(f[0]): scanfile = merge(path, f[0]) h = open(scanfile) linenumber = 1 for line in h: if target in line: hit = '{0}:\t(Line {1})\t{2}'.format( scanfile, linenumber, line) if output != '': with open(output, 'a') as op: op.write(hit) else: print(hit, end='') linenumber += 1 h.close()
def connect(self): prov = ProvisioningClient(self._id_scope, self._device_id, self._credentials_type, self._credentials, self._logger, self._model_id) creds = prov.register() self._mqtt_client = MQTTClient(self._device_id, creds.host, 8883, creds.user.encode('utf-8'), creds.password.encode('utf-8'), ssl=True, keepalive=60) self._commands_regex = ure.compile( '\$iothub\/methods\/POST\/(.+)\/\?\$rid=(.+)') self._mqtt_client.connect(False) self._connected = True self._logger.info('Device connected!') self._mqtt_client.set_callback(self._on_message) self._mqtt_client.subscribe(HubTopics.TWIN) self._mqtt_client.subscribe('{}/#'.format(HubTopics.PROPERTIES)) self._mqtt_client.subscribe('{}/#'.format(HubTopics.COMMANDS)) self._mqtt_client.subscribe('{}/#'.format( HubTopics.ENQUEUED_COMMANDS.format(self._device_id))) self._logger.debug(self._twin_request_id) self._mqtt_client.publish( HubTopics.TWIN_REQ.format(self._twin_request_id).encode('utf-8'), '{{}}')
def import_xpub(ln): # read an xpub/ypub/etc and return BIP32 node and what chain it's on. # - can handle any garbage line # - returns (node, chain, addr_fmt) # - people are using SLIP132 so we need this import tcc, chains, ure pat = ure.compile(r'.pub[A-Za-z0-9]+') found = pat.search(ln) if not found: return None found = found.group(0) for ch in chains.AllChains: for kk in ch.slip132: if found[0] == ch.slip132[kk].hint: try: node = tcc.bip32.deserialize(found, ch.slip132[kk].pub, ch.slip132[kk].priv) chain = ch addr_fmt = kk return (node, ch, kk) except ValueError: pass # looked like one, but fail. return None
def _compile(pattern, flags): # # internal: compile pattern # bypass_cache = flags & DEBUG # if not bypass_cache: # try: # p, loc = _cache[type(pattern), pattern, flags] # if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE): # return p # except KeyError: # pass if isinstance(pattern, _pattern_type): if flags: raise ValueError( "Cannot process flags argument with a compiled pattern") return pattern # if not sre_compile.isstring(pattern): # raise TypeError("first argument must be string or compiled pattern") # p = sre_compile.compile(pattern, flags) p = ure.compile(pattern, flags) ### # if not bypass_cache: # if len(_cache) >= _MAXCACHE: # _cache.clear() # if p.flags & LOCALE: # if not _locale: # return p # loc = _locale.setlocale(_locale.LC_CTYPE) # else: # loc = None # _cache[type(pattern), pattern, flags] = p, loc return p
def find_in_file(self, pattern, col, end): try: from ure import compile except: from re import compile #define REGEXP 1 Editor.find_pattern = pattern ## remember it if Editor.case != "y": pattern = pattern.lower() try: rex = compile(pattern) except: self.message = "Invalid pattern: " + pattern return -1 scol = col for line in range(self.cur_line, end): l = self.content[line] if Editor.case != "y": l = l.lower() ## since micropython does not support span, a step-by_step match has to be performed ecol = 1 if pattern[0] == '^' else len(l) + 1 for i in range(scol, ecol): match = rex.match(l[i:]) if match: ## bingo! self.col = i self.cur_line = line return len(match.group(0)) scol = 0 else: self.message = pattern + " not found" return -1
class TextSensorDataParser: SENSOR_REGEX = '([A-Z]*)([0-9]*)?\:(\-?[0-9]*\.?[0-9]*]*)' SENSOR_SEPARATOR = '|' regex = ure.compile(SENSOR_REGEX) def __init__(self, sensor_mapping): self.__sensor_mapping = sensor_mapping def is_buffer_parsable(self, buffer): return buffer.endswith(self.SENSOR_SEPARATOR) def parse(self, text_buffer): text_buffer = text_buffer[:-1] sensors = [] for sensor_data in text_buffer.split('|'): sensor_components = self.regex.search(sensor_data) if not sensor_components: continue mapping = self.__sensor_mapping[sensor_components.group(1)] sensors.append({ 'type': mapping[0], 'id': mapping[1], 'value': sensor_components.group(3) }) return sensors
def find_in_file(self, pattern, col, end): try: from ure import compile except: from re import compile Editor.find_pattern = pattern if Editor.case != "y": pattern = pattern.lower() try: rex = compile(pattern) except: self.message = "Invalid pattern: " + pattern return -1 scol = col for line in range(self.cur_line, end): l = self.content[line] if Editor.case != "y": l = l.lower() ecol = 1 if pattern[0] == '^' else len(l) + 1 for i in range(scol, ecol): match = rex.match(l[i:]) if match: self.col = i self.cur_line = line return len(match.group(0)) scol = 0 else: self.message = pattern + " not found" return -1
def __compile_regex(self, url): try: self.regex_str = "^{p}\S+".format(p=self.file_path) return ure.compile(self.regex_str), [] except: raise CompileRegexException( "Error with compiling regex in static route class!")
def __init__(self, url_pattern): self.pattern = '' self.args = [] use_regex = False for segment in url_pattern.lstrip('/').split('/'): if segment and segment[0] == '<': if segment[-1] != '>': raise ValueError('invalid URL pattern') segment = segment[1:-1] if ':' in segment: type_, name = segment.rsplit(':', 1) else: type_ = 'string' name = segment if type_ == 'string': pattern = '[^/]+' elif type_ == 'int': pattern = '\\d+' elif type_ == 'path': pattern = '.+' elif type_.startswith('re:'): pattern = type_[3:] else: raise ValueError('invalid URL segment type') use_regex = True self.pattern += '/({pattern})'.format(pattern=pattern) self.args.append({'type': type_, 'name': name}) else: self.pattern += '/{segment}'.format(segment=segment) if use_regex: self.pattern = re.compile('^' + self.pattern + '$')
def split_request(self, request): method = "" path = "" queryStrings = {} params = {} if isinstance(request, bytes): request = request.decode('ascii') try: regex = compile("[\r\n]") request_per_line = regex.split(request) firstLine = str(request_per_line[0]) method, url, _ = firstLine.split(" ") path = url if len(url.split("?")) == 2: path, queryString = url.split("?") queryStrings = queryString.split("&") for item in queryStrings: k, v = item.split("=") params[b"%s" % k] = b"%s" % v except: print("> Bad request: " + request) return method, path, params
def add_route(self, verb, path, function): # default priority is number of slashes -> longer matches preferred priority = path.count('/') if not path.endswith('$'): path = path + '$' self.routes.setdefault(verb, []).append((priority, path, ure.compile(path), function)) return function
def __compile_regex(self, url): try: log.debug("Compile url to regex.") self.num_slashes = [] slash = 0 params = [] current_param = "" param_reading = False self.regex_str = "^" for char in url: if char is "{": self.num_slashes.append(slash) param_reading = True elif char is "}": param_reading = False params.append(current_param) self.regex_str += "\w+" current_param = "" elif param_reading: current_param += char else: self.regex_str += char slash = slash + 1 if char is "/" else slash self.regex_str += "$" return ure.compile(self.regex_str), params except: raise CompileRegexException( "Error with compiling regex in route class!")
def handle(conn): byteRequest = conn.recv(1024) request = byteRequest.decode('utf-16') getHeightRequest = request.find('/height') setHeightRequest = request.find('?height') cancelRequest = request.find('/cancel') statusCode = 200 responseDict = {} if getHeightRequest >= 0: responseDict["height"] = str(desk.getHeight()) elif cancelRequest >= 0: responseDict["msg"] = "Adjustment Cancelled" desk.cancel() elif setHeightRequest >= 0: desk.stop() regex = ure.compile("^GET.\/\?height=([0-9]*)") matches = regex.match(request) if matches is not None: height = int(regex.match(request).group(1)) responseDict["height"] = height desk.setTargetHeight(height) else: statusCode = 400 responseDict["error"] = "Unable to process height value." else: statusCode = 404 responseDict["error"] = "No endpoint found" return statusCode, responseDict
def server(config, stripData, micropython_optimize=False): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: try: conn, addr = s.accept() request = conn.recv(4096) print(conn) request = re.compile('\r?\n').split(request.decode('utf-8')) method, path, protocol = request[0].split() response = "" parseGet = get(path) if parseGet["cmd"] == "static": response = parseGet["content"] else: if parseGet["cmd"] == "get" and parseGet["route"][ 0] in routes.routes: response = routes.routes[parseGet["route"][0]]( parseGet["route"][1:], parseGet["params"], stripData) print(response, response == "") if response == "": response = open('client/index.html', 'r').read() except ValueError: response = open('client/index.html', 'r').read() conn.send(response) conn.close()
def splittype(url): ### import ure ### _typeprog = ure.compile('^([^/:]+):') ### match = _typeprog.match(url) ### if match: ### scheme = match.group(1) ### return scheme.lower(), url[len(scheme) + 1:] ### return None, url ###
def add_route(self, verb, path, function): # default priority is number of slashes -> longer matches preferred priority = path.count('/') if not path.endswith('$'): path = path + '$' self.routes.setdefault(verb, []).append( (priority, path, ure.compile(path), function)) return function
def _compile(pattern, flags): if isinstance(pattern, _pattern_type): if flags: raise ValueError( "Cannot process flags argument with a compiled pattern") return pattern p = ure.compile(pattern, flags) ### return p
def __init__(self, pkg, routes=None, serve_static=True): if routes: self.url_map = routes else: self.url_map = [] if pkg and pkg != "__main__": self.pkg = pkg.split(".", 1)[0] else: self.pkg = None if serve_static: self.url_map.append((re.compile("^/(static/.+)"), self.handle_static)) self.mounts = [] self.inited = False # Instantiated lazily self.template_loader = None self.headers_mode = "parse"
def find_in_file(self, pattern, col, end): if is_micropython: from ure import compile else: from re import compile Editor.find_pattern = pattern ## remember it if Editor.case != "y": pattern = pattern.lower() try: rex = compile(pattern) except: self.message = "Invalid pattern: " + pattern return None start = self.cur_line if (col > len(self.content[start]) or # After EOL (pattern[0] == '^' and col != 0)): # or anchored and not at BOL start, col = start + 1, 0 # Skip to the next line for line in range(start, end): l = self.content[line][col:] if Editor.case != "y": l = l.lower() match = rex.search(l) if match: # Bingo self.cur_line = line ## Instead of match.span, a simple find has to be performed to get the cursor position. ## And '$' has to be treated separately, so look for a true EOL match first if pattern[-1:] == "$" and match.group(0)[-1:] != "$": self.col = col + len(l) - len(match.group(0)) else: self.col = col + l.find(match.group(0)) return len(match.group(0)) col = 0 else: self.message = pattern + " not found (again)" return None
# test splitting with pattern matches that can be empty # # CPython 3.5 issues a FutureWarning for these tests because their # behaviour will change in a future version. MicroPython just stops # splitting as soon as an empty match is found. try: import ure as re except ImportError: print("SKIP") raise SystemExit r = re.compile(" *") s = r.split("a b c foobar") print(s) r = re.compile("x*") s = r.split("foo") print(s) r = re.compile("x*") s = r.split("axbc") print(s)
def A(): return "A" print(re.sub('a', A(), 'aBCBABCDabcda.')) print( re.sub( r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', 'static PyObject*\npy_\\1(void){\n return;\n}\n', '\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():' ) ) print( re.compile( '(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)' ).sub( r'\g<1> colore \2 con \g<3> colore \4? ...', 'calzino blu e scarpa verde' ) ) # no matches at all print(re.sub('a', 'b', 'c')) # with maximum substitution count specified print(re.sub('a', 'b', '1a2a3a', 2)) # invalid group try: re.sub('(a)', 'b\\2', 'a') except: print('invalid group')
# init pin for dht11 dat = Pin(DHT_PIN, Pin.OPEN_DRAIN) dat(1) # freezing -> did we already send the sms ? don't send it twice freezing = False # set the clock c = untplib.NTPClient() rtclock = RTC() clock_adjust() # set the regex for the uart answers re = ure.compile("\r\nOK\r\n") er = ure.compile("\r\nERROR\r\n") # config the uart and see if somethings answers uart = UART(1, baudrate=115200, pins=(TX_PIN, RX_PIN)) # uart #, baudrate, pins tx,rx uart.write('+++') uart.write('AT+COPS?\r\n') time.sleep(1) while uart.any() != 0: print(uart.readall()) # get the battery adc = ADC() bat = adc.channel(pin=BAT_PIN) # initialize Blynk
if x not in scopes: scopes[x] = scope_count scope_count += 1 self.scopes.append({"name": x, "brackets": [entry]}) else: self.scopes[scopes[x]]["brackets"].append(entry) except Exception, e: bh_logging(e) if len(self.brackets): bh_debug( "Search patterns:\n" + "(?:%s)\n" % '|'.join(self.find_regex) + "(?:%s)" % '|'.join(self.sub_find_regex) ) self.sub_pattern = ure.compile("(?:%s)" % '|'.join(self.sub_find_regex), ure.MULTILINE | ure.IGNORECASE) self.pattern = ure.compile("(?:%s)" % '|'.join(self.find_regex), ure.MULTILINE | ure.IGNORECASE) self.enabled = True def init_match(self): """ Initialize matching for the current view's syntax. """ self.chars = 0 self.lines = 0 syntax = self.view.settings().get('syntax') language = basename(syntax).replace('.tmLanguage', '').lower() if syntax != None else "plain text" if language != self.view_tracker[0] or self.view.id() != self.view_tracker[1]: self.init_bracket_regions()
import ure as re r = re.compile('( )') try: s = r.split("a b c foobar") except NotImplementedError: print('NotImplementedError')
return min(int(page), 1) @app.route('/', methods=['GET', 'POST']) def homepage(request, response): if request.method == 'POST': print(request.headers) yield from request.read_form_data() if request.form.get('content'): note_id = Note.create(content=request.form['content'][0]) note = list(Note.get_id(note_id))[0] print("note after create:", note) tmpl = app._load_template('note.html') yield from picoweb.start_response(response, "application/json") yield from response.awriteiter(ijson.idumps({'note': tmpl(note), 'success': 1})) return yield from picoweb.jsonify(response, {'success': 0}) return yield from picoweb.start_response(response) # notes = Note.public().paginate(get_page(), 50) notes = Note.public() yield from app.render_template(response, 'homepage.html', (notes,)) @app.route(re.compile('^/archive/(.+)'), methods=['POST']) def archive_note(request, response): pkey = picoweb.utils.unquote_plus(request.url_match.group(1)) print("archive_note", pkey) Note.update({"timestamp": pkey}, archived=1) yield from picoweb.jsonify(response, {'success': True})
# test printing debugging info when compiling import ure ure.compile('^a|b[0-9]\w$', ure.DEBUG)
def test_re(r): try: re.compile(r) print("OK") except: # uPy and CPy use different errors, so just ignore the type print("Error")
import gpio import ddns import util pkg = ['ap', 'gpio', 'ddns'] for i in pkg: lib = __import__(i) lib.model.setup() routes = [ ('/cfg', util.handler(config.crud)), ('/cfg/reset', util.handler(config.reset)), ('/cfg/factory', util.handler(config.factory)), ('/sta', util.handler(sta.crud)), ('/sta/scan', util.handler(sta.scan)), ('/ap', util.handler(ap.ctl.crud)), ('/pwm', util.handler(pwm.list)), (re.compile('^/pwm/(\w+)$'), util.handler(pwm.crud)), (re.compile('^/pwm/(\w+)/duty$'), util.handler(pwm.duty)), ('/gpio', util.handler(gpio.ctl.list)), (re.compile('^/gpio/(\w+)$'), util.handler(gpio.ctl.crud)), (re.compile('^/ddns$'), util.handler(ddns.ctl.crud)), (re.compile('^(.*)$'), util.handler(util.static)) ] app = picoweb.WebApp(__name__, routes, False) app.run(host="0.0.0.0", port=80) import uasyncio as asyncio loop = asyncio.get_event_loop() loop.run_forever()
try: import ure as re except ImportError: import re r = re.compile(".+") m = r.match("abc") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") r = re.compile("(.+)1") m = r.match("xyz781") print(m.group(0)) print(m.group(1)) try: m.group(2) except IndexError: print("IndexError") r = re.compile("[a-cu-z]") m = r.match("a") print(m.group(0)) m = r.match("z") print(m.group(0)) m = r.match("d") print(m) m = r.match("A") print(m)
try: import ure as re except ImportError: import re r = re.compile(" ") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar", 1) print(s) r = re.compile(" +") s = r.split("a b c foobar", 2) print(s) r = re.compile(" *") s = r.split("a b c foobar") # TODO - no idea how this is supposed to work, per docs, empty match == stop # splitting, so CPython code apparently does some dirty magic. #print(s) r = re.compile("x*") s = r.split("foo") print(s)
try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit r = re.compile(" ") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar", 1) print(s) r = re.compile(" +") s = r.split("a b c foobar", 2) print(s) r = re.compile("[a-f]+") s = r.split("0a3b9") print(s) # bytes objects r = re.compile(b"x")
### Author: EMF Badge team ### Description: Model and Helpers for TiLDA apps and the App Library API ### License: MIT import os, ure, http_client import filesystem EMF_USER = "******" USER_NAME_SEPARATOR = "~" ATTRIBUTE_MATCHER = ure.compile("^\s*###\s*([^:]*?)\s*:\s*(.*)\s*$") # Yeah, regex! CATEGORY_ALL = "all" CATEGORY_NOT_SET = "uncategorised" class App: """Models an app and provides some helper functions""" def __init__(self, folder_name, api_information = None): self.folder_name = self.name = folder_name.lower() self.user = EMF_USER if USER_NAME_SEPARATOR in folder_name: [self.user, self.name] = folder_name.split(USER_NAME_SEPARATOR, 1) self.user = self.user.lower() self.name = self.name.lower() self._attributes = None # Load lazily self.api_information = api_information @property def folder_path(self): return "apps/" + self.folder_name @property def main_path(self):
try: import ure as re except ImportError: import re r = re.compile(".+") m = r.match("abc") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") r = re.compile("(.+)1") m = r.match("xyz781") print(m.group(0)) print(m.group(1)) try: m.group(2) except IndexError: print("IndexError") r = re.compile("o+") m = r.search("foobar") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError")
def hello(req, resp): yield from picoweb.start_response(resp) # Here's how you extract matched groups from a regex URI match yield from resp.awrite("Hello " + req.url_match.group(1)) ROUTES = [ # You can specify exact URI string matches... ("/", index), ("/squares", squares), ("/file", lambda req, resp: (yield from app.sendfile(resp, "example_webapp.py"))), # ... or match using a regex, the match result available as req.url_match # for match group extraction in your view. (re.compile("^/iam/(.+)"), hello), ] import ulogging as logging logging.basicConfig(level=logging.INFO) #logging.basicConfig(level=logging.DEBUG) app = picoweb.WebApp(__name__, ROUTES) # debug values: # -1 disable all logging # 0 (False) normal logging: requests and errors # 1 (True) debug logging # 2 extra debug logging app.run(debug=1)
<!DOCTYPE html> <html> <head> <link href="style.css" rel="stylesheet"> </head> <body> <p>The style.css should be cached and might be encoded.</p> <p class="green">Check out your webdev tool!</p> </body> </html>""") # Send gzipped content if supported by client. # Shows specifying headers as a flat binary string - # more efficient if such headers are static. @app.route(re.compile('^\/(.+\.css)$')) def styles(req, resp): file_path = req.url_match.group(1) headers = b"Cache-Control: max-age=86400\r\n" if b"gzip" in req.headers.get(b"Accept-Encoding", b""): file_path += ".gz" headers += b"Content-Encoding: gzip\r\n" print("sending " + file_path) yield from app.sendfile(resp, "static/" + file_path, "text/css", headers) import ulogging as logging logging.basicConfig(level=logging.INFO)
try: import ure as re except ImportError: try: import re except ImportError: import sys print("SKIP") sys.exit() r = re.compile(".+") m = r.match("abc") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") # conversion of re and match to string str(r) str(m) r = re.compile("(.+)1") m = r.match("xyz781") print(m.group(0)) print(m.group(1)) try: m.group(2) except IndexError: print("IndexError")
return dt def parse_date(dtstr, dt=None): """Parses date from NMEA date format into Datetime object""" if not dt: dt = Datetime() dt.day = int(dtstr[0:2]) dt.month = int(dtstr[2:4]) dt.year = 2000 + int(dtstr[4:]) return dt # Adapted from https://github.com/Knio/pynmea2/blob/master/pynmea2/nmea_utils.py dm_to_sd_re = re.compile(r'^(\d+)(\d\d\.\d+)$') def dm_to_sd(dm): """Converts the NMEA dddmm.mmmm format to the more commonly used decimal format""" if ( not dm or dm == '0'): return 0.0 match = dm_to_sd_re.match(dm) d = match.group(1) m = match.group(2) return float(d) + float(m) / 60 def parse_gprmc(line, fix=None): """Parses G[PLN]RMC sentence, returns a Fix object. NOTE: The line must be a string, not bytearray. Cast before passing""" if not fix: fix = Fix()