本文整理汇总了Python中re.fullmatch函数的典型用法代码示例。如果您正苦于以下问题:Python fullmatch函数的具体用法?Python fullmatch怎么用?Python fullmatch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fullmatch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, record):
tokens = re.split("\s+", record.strip())
self.data = {}
if len(tokens) == self.AUTH_COLCOUNT:
if not (
(re.fullmatch(self.AUTH_TAGNO_VALID_REGEX, tokens[self.AUTH_NDX_TAGNO]) != None)
and (re.fullmatch(self.AUTH_SN_VALID_REGEX, tokens[self.AUTH_NDX_SN]) != None)
and (re.fullmatch(self.AUTH_AUTHCODE_VALID_REGEX, tokens[self.AUTH_NDX_DP1_AUTH]) != None)
):
raise AuthMalformedRecordExcept
self.data[self.AUTH_KEY_TAGNO] = tokens[self.AUTH_NDX_TAGNO]
self.data[self.AUTH_KEY_SN] = tokens[self.AUTH_NDX_SN]
self.data[self.AUTH_KEY_CFG_AUTH] = tokens[self.AUTH_NDX_CFG_AUTH]
self.data[self.AUTH_KEY_SFN_AUTH] = tokens[self.AUTH_NDX_SFN_AUTH]
self.data[self.AUTH_KEY_DP1_AUTH] = tokens[self.AUTH_NDX_DP1_AUTH]
self.data[self.AUTH_KEY_DP2_AUTH] = tokens[self.AUTH_NDX_DP2_AUTH]
self.data[self.AUTH_KEY_DP3_AUTH] = tokens[self.AUTH_NDX_DP3_AUTH]
self.data[self.AUTH_KEY_DP4_AUTH] = tokens[self.AUTH_NDX_DP4_AUTH]
else:
raise AuthBadColumnCountExcept
示例2: select
def select(self, station=None, channel=None, location=None, component=None):
# A new Stream object is returned but the traces it contains are just aliases to the traces of the original stream.
# Does not copy the data but only passes a reference.
# all matching done using regular expressions (module re)
traces = []
for trace in self:
# skip trace if any given criterion is not matched
if station is not None:
station = station.upper()
if not re.fullmatch(station, trace.station):
continue
if location is not None:
if not re.fullmatch(location, trace.location):
continue
if channel is not None:
channel = channel.upper()
if not re.fullmatch(channel, trace.channel):
continue
if component is not None:
component = component.upper()
if len(trace.channel) < 3:
continue
if not (trace.channel[-1] == component):
continue
traces.append(trace)
return self.__class__(traces=traces)
示例3: read_spatiocyte_input
def read_spatiocyte_input(filename):
with open(filename, 'r') as f:
header = f.readline().rstrip().split(',')
if len(header) < 5:
raise RuntimeError('The file given [{}] was invalid: "{}"'.format(filename, header))
interval, lz, ly, lx, voxel_radius = [float(_) for _ in header[: 5]]
species_info = header[5: ]
lengths = numpy.array([lx, ly, lz], dtype=numpy.float64) * 2 * voxel_radius # meter
species_ids = {}
for sp in species_info:
# ex) [/Cell/Membrane:S1][0]=2e-08
mobj = re.fullmatch(r'\[(.*)\]\[(\d+)\]=(.*)', sp)
if mobj is None:
warnings.warn('An invalid species info [{}] was given. Check [{}]'.format(sp, filename))
continue
sp_id = mobj.group(1)
sp_idx = int(mobj.group(2))
radius = float(mobj.group(3))
if re.fullmatch(r'(\/|(\/[^\/]+)+):([^\/:]+)', sp_id) is None:
warnings.warn('A species ID is invalid [{}]. Ignored'.format(sp))
continue
_log.info(" Species [{}] => ID={}, Radius={}".format(sp_idx, sp_id, radius))
species_ids[sp_idx] = (sp_id, radius)
_log.info(' Time Interval = {} sec'.format(interval))
_log.info(' Voxel radius = {} m'.format(voxel_radius))
_log.info(' Compartment lengths: {} nm x {} nm x {} nm'.format(lengths[0], lengths[1], lengths[2]))
_log.info(' Species IDs: {}'.format(', '.join([sp_id for sp_id, _ in species_ids.values()])))
return dict(interval=interval, lengths=lengths, voxel_radius=voxel_radius, species_ids=species_ids)
示例4: detect_language
def detect_language(title):
"""
Detect language of a given title. The matching is case-sensitive and spaces are
treated the same way as underscores.
:param title: page title to work with
:returns: a ``(pure, lang)`` tuple, where ``pure`` is the pure page title without
the language suffix and ``lang`` is the detected language in long, localized form
"""
title_regex = r"(?P<pure>.*?)[ _]\((?P<lang>[^\(\)]+)\)"
pure_suffix = ""
# matches "Page name/Subpage (Česky)"
match = re.fullmatch(title_regex, title)
# matches "Page name (Česky)/Subpage"
if not match and "/" in title:
base, pure_suffix = title.split("/", maxsplit=1)
pure_suffix = "/" + pure_suffix
match = re.fullmatch(title_regex, base)
# matches "Category:Česky"
if not match:
match = re.fullmatch(r"(?P<pure>[Cc]ategory[ _]?\:[ _]?(?P<lang>[^\(\)]+))", title)
if match:
lang = match.group("lang")
if lang in get_language_names():
return match.group("pure") + pure_suffix, lang
return title, get_local_language()
示例5: helper_cassini_valid_obs_name
def helper_cassini_valid_obs_name(obs_name):
"""Check a Cassini observation name to see if it is parsable. Such a
name will have four parts separated by _:
<PRIME> _ <REVNO> <TARGETCODE> _ <ACTIVITYNAME> <ACTIVITYNUMBER> _ <INST>
or, in the case of VIMS (sometimes):
<PRIME> _ <REVNO> <TARGETCODE> _ <ACTIVITYNAME> <ACTIVITYNUMBER>
<PRIME> can be: ([A-Z]{2,5}|22NAV)
- '18ISS', '22NAV', 'CIRS', 'IOSIC', 'IOSIU', 'IOSIV', 'ISS',
'NAV', 'UVIS', 'VIMS'
- If <INST> is 'PRIME' or 'PIE' then <PRIME> can only be one of:
'22NAV', 'CIRS', 'ISS', 'NAV', 'UVIS', 'VIMS'
<REVNO> can be: ([0-2]\d\d|00[A-C]|C\d\d)
- 000 to 299
- 00A to 00C
- C00 to C99
<TARGETCODE> can be: [A-Z]{2}
- See _CASSINI_TARGET_CODE_MAPPING
<ACTIVITYNAME> can be: [0-9A-Z]+
- Everything except the final three digits
<ACTIVITYNUMBER> can be: \d\d\d
- Last final three digits
<INST> can be one of: [A-Z]{2,7}
- 'PRIME', 'PIE' (prime inst is in <PRIME>)
- 'CAPS', 'CDA', 'CIRS', 'INMS', 'ISS', 'MAG', 'MIMI', 'NAV', 'RADAR',
'RPWS', 'RSS', 'SI', 'UVIS', 'VIMS'
- Even though these aren't instruments, it can also be:
'AACS' (reaction wheel assembly),
'ENGR' (engineering),
'IOPS',
'MP' (mission planning),
'RIDER', 'SP', 'TRIGGER'
If <INST> is missing but everything else is OK, we assume it's PRIME
"""
if obs_name is None:
return False
ret = re.fullmatch(
'([A-Z]{2,5}|22NAV)_([0-2]\d\d|00[A-C]|C\d\d)[A-Z]{2}_[0-9A-Z]+\d\d\d_[A-Z]{2,7}',
obs_name)
if ret:
return True
# Try without _INST
ret = re.fullmatch(
'([A-Z]{2,5}|22NAV)_([0-2]\d\d|00[A-C]|C\d\d)[A-Z]{2}_[0-9A-Z]+\d\d\d',
obs_name)
if ret:
return True
return False
示例6: _last_rid_from_results
def _last_rid_from_results(self):
r = -1
try:
day_folders = os.listdir(self.results_dir)
except:
return r
day_folders = filter(
lambda x: re.fullmatch("\\d\\d\\d\\d-\\d\\d-\\d\\d", x),
day_folders)
for df in day_folders:
day_path = os.path.join(self.results_dir, df)
try:
hm_folders = os.listdir(day_path)
except:
continue
hm_folders = filter(lambda x: re.fullmatch("\\d\\d(-\\d\\d)?", x),
hm_folders)
for hmf in hm_folders:
hm_path = os.path.join(day_path, hmf)
try:
h5files = os.listdir(hm_path)
except:
continue
for x in h5files:
m = re.fullmatch(
"(\\d\\d\\d\\d\\d\\d\\d\\d\\d)-.*\\.h5", x)
if m is None:
continue
rid = int(m.group(1))
if rid > r:
r = rid
return r
示例7: _last_rid_from_results
def _last_rid_from_results(self):
r = -1
try:
day_folders = os.listdir(self.results_dir)
except:
return r
day_folders = filter(lambda x: re.fullmatch('\d\d\d\d-\d\d-\d\d', x),
day_folders)
for df in day_folders:
day_path = os.path.join(self.results_dir, df)
try:
minute_folders = os.listdir(day_path)
except:
continue
minute_folders = filter(lambda x: re.fullmatch('\d\d-\d\d', x),
minute_folders)
for mf in minute_folders:
minute_path = os.path.join(day_path, mf)
try:
h5files = os.listdir(minute_path)
except:
continue
for x in h5files:
m = re.fullmatch('(\d\d\d\d\d\d\d\d\d)-.*\.h5', x)
if m is None:
continue
rid = int(m.group(1))
if rid > r:
r = rid
return r
示例8: get_last_rid
def get_last_rid():
r = -1
try:
day_folders = os.listdir("results")
except:
return r
day_folders = filter(lambda x: re.fullmatch('\d\d\d\d-\d\d-\d\d', x),
day_folders)
for df in day_folders:
day_path = os.path.join("results", df)
try:
minute_folders = os.listdir(day_path)
except:
continue
minute_folders = filter(lambda x: re.fullmatch('\d\d-\d\d', x),
minute_folders)
for mf in minute_folders:
minute_path = os.path.join(day_path, mf)
try:
h5files = os.listdir(minute_path)
except:
continue
for x in h5files:
m = re.fullmatch('(\d\d\d\d\d\d\d\d\d)-.*\.h5', x)
rid = int(m.group(1))
if rid > r:
r = rid
return r
示例9: handle_request
def handle_request(self, data=None):
"""Handles both POST and GET reqs.
In case of GET there's no data.
It also extracts data from the url path (regex groups) and passes it to
the appropriate end-handler func. """
thread_name = threading.current_thread().name
print(thread_name, self.raw_requestline)
# resolve request path to end-handler function
# (url) unquote the request path so that eventual unicode codes (%<code>) are converted back to unicode chars
delegations = [(re.fullmatch(url_pattern, unquote(self.path)), action)
for url_pattern, action in BackOfficeReqHandler.REQUEST_HANDLERS.items()
if re.fullmatch(url_pattern, unquote(self.path)) is not None]
# for an existing request path there should be exactly one handler func.
if len(delegations) == 1:
delegate = delegations[0]
args = self,
if data is not None: # if there is POST data
args = args + (data,)
for group in delegate[0].groups(): # if there are more args to be extracted from the request url (e.g. user, month, year)
args = args + (group,)
try:
return delegate[1](*args) # call the appropriate handler func
finally:
self.wfile.flush()
else: # error: page doesn't exist
self.send_response(404)
self.end_headers()
self.wfile.write(str.encode("The requested page {page} is not found!".format(page=self.path), 'utf-8'))
self.wfile.flush()
return
示例10: isemail
def isemail(str):
if str == "":
return 0
else:
if re.match(r"[a-zA-Z_0-9$?&][email protected]", str):
str1, str2 = str.split("@", 1) # str1 is before '@', str2 is after '@'
if re.fullmatch(r"[a-zA-Z0-9]+.[a-zA-Z0-9]+", str2) or re.fullmatch(
r"[a-zA-Z0-9]+.[a-zA-Z0-9]+.[a-zA-Z0-9]+", str2
):
domainList = str2.split(".")
domainValidation = [
map(
lambda x: 1 if len(x) <= 63 and x[0].isalpha() and (x[-1].isalpha() or x[-1].isdigit()) else 0,
domainList,
)
]
if domainValidation.count(0) == 0:
return 1
else:
return 0
else:
return 0
else:
return 0
示例11: inputConsole
def inputConsole(inputVerseFilePath):
consoleInput = input('Please write one or several verse numbers separated by a comma to see their variance in Goethes Faust')
#do stuff with consoleInput
inputLineList = []
fileList=[] #delete either the global variable fileList or the local one
with open (inputVerseFilePath,'r', encoding='utf-8') as f:
verseFilePathDict = json.load(f, encoding='utf-8')
if (re.fullmatch('\d{1,6}', consoleInput)):
if not (verseFilePathDict.get(consoleInput)):
print('Can not find line ' + consoleInput)
else:
fileList = verseFilePathDict[consoleInput]
inputLineList.append(consoleInput)
else:
inputTempList = re.split('\d{1,6}', consoleInput)
for inputTemp in inputTempList:
if (re.fullmatch('\d{1,6}', inputTemp)):
if not (verseFilePathDict.get(consoleInput)):
print('Can not find line ' + consoleInput)
else:
fileList.append(verseFilePathDict[inputTemp])
inputLineList.append(inputTemp)
parseXML(fileList,inputLineList)
示例12: match_date
def match_date(arg, data):
op, rest = _get_comparison_function(arg.lower(), keepspaces=True)
yearrx = re.fullmatch(r'(19|20)?(\d\d)', rest.strip())
monthyearrx = re.fullmatch(r'(\w+)\s*(\d{4})', rest.strip())
currentyear = date.today().year
if yearrx:
century, tens = yearrx.groups()
if yearrx.group(1) is None:
century = '19' if int('20'+tens) > currentyear else '20'
year = int(century + tens)
return op(data.year, year)
elif monthyearrx:
monthname, year = monthyearrx.groups()
try:
month = _monthabbrs.index(monthname)+1
except ValueError:
raise SyntaxError('Invalid month')
return op(data.year*12+data.month, int(year)*12+month)
else:
try:
fulldate = datetime.strptime(rest.strip(), '%Y-%m-%d').date()
except ValueError:
raise SyntaxError('Invalid date match expression')
else:
return op(data, fulldate)
示例13: __call__
def __call__(self, stream, meta):
match = re.fullmatch(r'\|\|(.+)', stream.peek())
if not match:
return False, None
dl = nodes.Container('dl')
while stream.has_next():
match = re.fullmatch(r'\|\|(.+)', stream.peek())
if match:
stream.next()
term = match.group(1).strip('|').strip()
dt = nodes.Leaf('dt').append(nodes.Text(term))
dl.append(dt)
definition = utils.LineStream()
while stream.has_next():
if re.fullmatch(r'\|\|(.+)', stream.peek()):
break
elif stream.peek().startswith(' ') or stream.peek() == '':
definition.append(stream.next())
else:
break
dd = nodes.Container('dd')
dd.children = ContainerParser().parse(definition.dedent(), meta)
dl.append(dd)
else:
break
return True, dl
示例14: db_fix
def db_fix(fingerprint): # add colons to fingerprints
bihex = "[0-9A-Fa-f]{2}"
if bool(re.fullmatch("(" + bihex + "[:]){0,}" + bihex, fingerprint)):
return fingerprint
elif bool(re.fullmatch("(" + bihex + "){1,}", fingerprint)):
return ":".join(chop(fingerprint, 2))
else: assert False, "Error: fingerprint is invalid"
示例15: is_realizable
def is_realizable(test):
spec_status = stripped_non_empty(readfile(test).splitlines())[-1]
if re.fullmatch('-- *realizable', spec_status):
return True
if re.fullmatch('-- *unrealizable', spec_status):
return False
assert 0, 'spec status is unknown'