def translate(value): try: from UnityEngine import Application from UnityEngine.UI import Translation from System.Text.RegularExpressions import Regex tdict = Translation.TextTranslator._TextTranslator__translationsLv[Application.loadedLevel] tval = tdict[value] if tval: return tval.Value tdict = Translation.TextTranslator._TextTranslator__translations tval = tdict[value] if tval: return tval.Value for kvp in Translation.TextTranslator._TextTranslator__translationsLvR[Application.loadedLevel]: m = Regex.Match(text, kvp.Key) if m.Success and (m.Groups.Item[0].Value == text): str = m.Result(kvp.Value) if str: return str break for kvp in Translation.TextTranslator._TextTranslator__translationsR: m = Regex.Match(text, kvp.Key) if m.Success and (m.Groups.Item[0].Value == text): str = m.Result(kvp.Value) if str: return str break except: return value
def check_created_image_regex(first_image_url, second_image_url, regex): matches = Regex.Matches(first_page_source._source, regex, RegexOptions.IgnoreCase) escaped_first_image_url = escape_uri_string(first_image_url) escaped_second_image_url = escape_uri_string(second_image_url) if matches.Count == 0: return False, 0 else: if debug: print "\nFound " + str( matches.Count ) + " match(es) on the first page with regex: " + regex print "Captured: " + matches[0].Value print "link group: " + matches[0].Groups["link"].Value #We don't care if there is more than one result. As long as the first result is the correct image result, image_uri = Uri.TryCreate(first_page_uri, matches[0].Groups["link"].Value) #Valid url and matches the input image url if result and image_uri.AbsoluteUri in (first_image_url, escaped_first_image_url): if debug: print "Valid uri and matches image url" else: if debug: print "Not a valid uri or doesn't match image url" return False, 0 matches_second = Regex.Matches(second_page_source._source, regex, RegexOptions.IgnoreCase) if matches_second.Count == 0: if debug: print "No matches on the second page" return False, 0 #Regex match on the second page. Same deal as above. We don't care if there is more than one result if debug: print "\nFound " + str( matches_second.Count) + " match(es) on the second page" print "Captured: " + matches_second[0].Value print "link group: " + matches_second[0].Groups["link"].Value result, image_uri = Uri.TryCreate( second_page_uri, matches_second[0].Groups["link"].Value) if result and image_uri.AbsoluteUri in (second_image_url, escaped_second_image_url): if debug: print "Regex works on both pages and returns the correct image" return True, matches.Count else: if debug: print "Invalid Uri or doesn't match the second image url" return False, 0 return False, matches.Count
def walk(folder): for file in IO.Directory.GetFiles(folder): if (Regex.IsMatch(file, "\.pyc") or not Regex.IsMatch(file, "\.py")): continue yield file for folder in IO.Directory.GetDirectories(folder): if (Regex.IsMatch(folder, "async")): continue for file in walk(folder): yield file
def replace_date_values(string): string = Regex.Replace(string, r"(?<=/)\d+(?=/)", r"(?<=/)\d+(?=/)", RegexOptions.IgnoreCase) string = Regex.Replace( string, r"(?<=/)(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)(?=/)", r"(?<=/)(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)(?=/)", RegexOptions.IgnoreCase) return string
def check_regex_against_source(regex, check_value, check_value2): matches = Regex.Matches(first_page_source._source, regex._regex, RegexOptions.IgnoreCase) if matches.Count != 0: if debug: print "\n\nFound " + str( matches.Count ) + " match(es) on the first page with regex: " + regex._regex print "Captured: " + matches[0].Value print "link group: " + matches[0].Groups["link"].Value #We don't care if there is more than one result. As long as the first result is the correct image result, result_uri = Uri.TryCreate(first_page_uri, matches[0].Groups["link"].Value) if result and result_uri.AbsoluteUri in (check_value, check_value2): #Valid url and matches against the check_value if debug: print "Valid uri" else: return False matches_second = Regex.Matches(second_page_source._source, regex._regex, RegexOptions.IgnoreCase) if matches_second.Count == 0: if debug: print "No matches found on the second page" return False #Regex match on the second page. Same deal as above. We don't care if there is more than one result if debug: print "\nFound " + str( matches_second.Count) + " match(es) on the second page" print "Captured: " + matches_second[0].Value print "link group: " + matches_second[0].Groups["link"].Value result, result_uri = Uri.TryCreate( second_page_uri, matches_second[0].Groups["link"].Value) if result: regex._matches = matches.Count if debug: print "Added to valid regex" return regex else: if debug: print "Invalid uri" return False return False
def regexReplace(self, myString, myVals): ''' todo: this *might* work! ''' #myString = 'der Hugo' #oldVal = r'\w*' #newVal = r'$&$&' regexp = Regex(myVals[0], RegexOptions.IgnoreCase | RegexOptions.Singleline) return regexp.Replace(myString, myVals[1])
def generateProjectCode(actionContext): currentYear = DateTime.Today.ToString('yy') regexString = String.Format("^P{0}-(\d+)$", currentYear) regex = Regex(regexString) def getLastProjectCode(projectCodes): numbers = projectCodes.Select(lambda c: regex.Match(c.Code)) numbers = numbers.Where(lambda m: m.Success) numbers = numbers.Select( lambda m: Convert.ToDecimal(m.Groups[1].Captures[0].Value)) return numbers.Max() dc = actionContext.DataContext if actionContext.InputSet <> None: for newProject in actionContext.InputSet.Take(1): if newProject.Code == 'To Be Generated': projectCodesString = dc.Select( "From P In Project Order By Max(P.Code) Desc Select New With { P.Code, .Ma = Max(P.Code) }" ) if projectCodesString.Count == 0: newProjectCode = Convert.ToInt32(1) else: latestExistingProjectCode = getLastProjectCode( projectCodesString) newProjectCode = Convert.ToInt32( latestExistingProjectCode) + 1 if newProjectCode < 10: newProject.Code = newProjectCode.ToString() else: newProject.Code = newProjectCode.ToString()
def ReplacePaddedFrame(self, arguments, pattern, frame): frameRegex = Regex(pattern) while True: frameMatch = frameRegex.Match(arguments) if frameMatch.Success: paddingSize = int(frameMatch.Groups[1].Value) if paddingSize > 0: padding = StringUtils.ToZeroPaddedString( frame, paddingSize, False) else: padding = str(frame) arguments = arguments.replace(frameMatch.Groups[0].Value, padding) else: break return arguments
def add_route(self, url, view, method): if self.strict_slashes and (len(url) == 0 or url[-1] != '/'): url += '/' url = '^%s$' % url r = Regex(url, RegexOptions.Compiled) self.routes.append((r, view, method))
def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def browserEnum(): summary = printHeader("BROWSER ENUM") regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') #Active IE Urls summary += printSubheader("ACTIVE EXPLORER URLS") app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application")) summary += "\n".join([w.LocationUrl() for w in app.Windows()]) #Chrome History summary += printSubheader("\n\nChrome History") try: cHistPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\History".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) cHist = open(cHistPath, "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(cHist)][-10:]) except: pass summary += printSubheader("\nChrome Bookmarks") #Chrome Bookmarks try: cBMPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\Bookmarks".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) js = JavaScriptSerializer() cBM = js.DeserializeObject(open(cBMPath, "r").read()) urls = cBM["roots"]["bookmark_bar"]["children"] for url in urls: u = url['url'] d = url['name'] summary += "[*] {0}\n{1}\n\n".format(d, u) except: pass summary += printSubheader("Firefox History") #Firefox History try: regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') fHistPath = "{0}\Users\{1}\AppData\Roaming\Mozilla\Firefox\Profiles".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) for path in DirectoryInfo(fHistPath).EnumerateDirectories("*.default"): places = open(path.FullName + "\places.sqlite", "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(places)][:10]) except: pass summary += printSubheader("IE History") typedUrlPath = "\Software\Microsoft\Internet Explorer\TypedURLs" for sid in Registry.Users.GetSubKeyNames(): if sid != ".DEFAULT" and not sid.endswith("Classes"): try: typedUrlsKey = Registry.Users.OpenSubKey(sid + typedUrlPath) if typedUrlsKey != None: summary += "[{0}][{1}]\n".format(sid, SecurityIdentifier(sid.ToString()).Translate(NTAccount)) for value in typedUrlsKey.GetValueNames(): summary += "\t{0}\n".format(typedUrlsKey.GetValue(value)) summary += "\n" except SystemError: pass return summary
def onDrawClipboard(s, e): global uriList if s == Application.Current.MainWindow: text = tryGetClipboardText() if text is not None: match = Regex.Match(text, "(\\S+)://([^:/]+)(:(\\d+))?(/[^#\\s]*)(#(\\S+))?", RegexOptions.CultureInvariant); if match.Success: success, uri = Uri.TryCreate(match.Value, UriKind.RelativeOrAbsolute) if success: if uri.IsAbsoluteUri and uriList.Contains(uri) == False: if not uri.Host.Equals("nazr.in"): uriList.Add(uri) if uriList.Count > 10: uriList.RemoveRange(0, uriList.Count - 10)
def Match(self, s): return Regex.IsMatch(s, self.regex)
from System.IO import StreamReader from System.IO import StringReader from System.IO import MemoryStream from System.Text import Encoding from System.Text.RegularExpressions import Regex from System.Text.RegularExpressions import RegexOptions from System.Xml import DtdProcessing from System.Xml import Formatting from System.Xml import ValidationType from System.Xml import XmlDocument from System.Xml import XmlNodeType from System.Xml import XmlReader from System.Xml import XmlReaderSettings from System.Xml import XmlTextWriter CRE_ENCODING = Regex("encoding=['\"](?<enc_name>.*?)['\"]", RegexOptions.Compiled) __all__ = [ 'CLRXMLTreeParser', 'attach_namespaces', 'prettify_string', ] def prettify_string(rough_string): """Return an XML string with added whitespace for legibility, using .NET infrastructure. Parameters ---------- rough_string : str
def determine_status(self): if self.statusSet: return # PMM CHECKS checks_sql = "SELECT TOP 20 * FROM [BackgroundChecks] WHERE [PeopleId] = @p1 AND " \ "DATEDIFF(DAY, DATEADD(YEAR, -10, GETDATE()), [Updated]) > 0 ORDER BY [Updated] DESC". \ format(self.person.PeopleId) for check in q.QuerySql(checks_sql, self.person.PeopleId): check_status = 0 if check.StatusID >= 2: # Check has begun check_status = check_status | self.Statuses['CHECK_STARTED'] if check.StatusID == 3: # Check is complete check_status = check_status | self.Statuses[ 'CHECK_COMPLETE'] if check.IssueCount == 0: check_status = check_status | self.Statuses[ 'REVIEW_COMPLETE'] | self.Statuses['PASSED'] else: check_status = check_status | self.Statuses[ 'REVIEW_COMPLETE'] # TODO: establish a means for checks to pass with issues. if check.ServiceCode == "" and check.ReportLabelID == 1: # PA Employee self.statusHis[ 'paEmp'] = self.statusHis['paEmp'] | check_status if DateTime.Compare(check.Updated, self.Renewals['paEmp']) > 0: self.statusExp[ 'paEmp'] = self.statusExp['paEmp'] | check_status if DateTime.Compare(check.Updated, self.Expirations['paEmp']) > 0: self.statusCur[ 'paEmp'] = self.statusCur['paEmp'] | check_status if check.ServiceCode == "ComboPS": # PA Volunteer self.statusHis[ 'paVol'] = self.statusHis['paVol'] | check_status if DateTime.Compare(check.Updated, self.Renewals['paVol']) > 0: self.statusExp[ 'paVol'] = self.statusExp['paVol'] | check_status if DateTime.Compare(check.Updated, self.Expirations['paVol']) > 0: self.statusCur[ 'paVol'] = self.statusCur['paVol'] | check_status if check.ServiceCode == "Combo" or check.ServiceCode == "ComboPS" or check.ServiceCode == "": # Basic self.statusHis[ 'basic'] = self.statusHis['basic'] | check_status if DateTime.Compare(check.Updated, self.Renewals['basic']) > 0: self.statusExp[ 'basic'] = self.statusExp['basic'] | check_status if DateTime.Compare(check.Updated, self.Expirations['basic']) > 0: self.statusCur[ 'basic'] = self.statusCur['basic'] | check_status # MINOR'S WAIVER if self.person.BirthYear is not None and self.person.BirthDate > self.Expirations[ 'isMin']: self.statusCur['isMin'] = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \ self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED'] if self.person.BirthYear is not None and self.person.BirthDate > self.Renewals[ 'isMin']: self.statusExp['isMin'] = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \ self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED'] # FBI Fingerprinting for doc in self.person.VolunteerForms: rx = Regex( "(?<docType>\w+)\s+(?<date>[0-9]{1,2}/[0-9]{1,2}/[0-9]{4})", RegexOptions.Compiled | RegexOptions.IgnoreCase) rm = rx.Match(doc.Name) if not rm.Success: continue if rm.Groups['docType'].Value.ToLower() == "fbi": dt = Convert.ToDateTime(rm.Groups['date'].Value) # TODO impose some form of verification here. check_status = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \ self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED'] self.statusHis[ 'fingr'] = self.statusHis['fingr'] | check_status if DateTime.Compare(dt, self.Renewals['fingr']) > 0: self.statusExp[ 'fingr'] = self.statusExp['fingr'] | check_status if DateTime.Compare(dt, self.Expirations['fingr']) > 0: self.statusCur[ 'fingr'] = self.statusCur['fingr'] | check_status self.statusSet = True
# NPC Weight manipulator Plugin # # Enumerate through all NPCs and list/manipulate the weight # some mods like rbs.esp I think have too many fat people # import shared.required import System import TESVSnip.Domain from TESVSnip.Domain.Model import BaseRecord, Record, Plugin, SubRecord, GroupRecord from System import Action, Func, Predicate, TimeSpan from System.Diagnostics import Stopwatch from System.Text.RegularExpressions import Regex #from TESVSnip.UI.Hosting import ScriptSupport as ss reWhite = Regex( r"[\n\t\r]") # can probably use re but user might not have full IronPython def newByteArray(items): array = System.Array.CreateInstance(System.Byte, len(items)) for i, a in enumerate(items): array[i] = a return array def newPlugin(): p = Plugin() r = Record() r.Name = "TES4" sr = SubRecord() sr.Name = "HEDR"
def strings(p, rx): regx = Regex(rx, RegexOptions.Compiled) for s in Strings.SimpleRegex(regx, p): print s.Item1.ToString("X") + " " + s.Item2
def create_image_regex(first_image_url, second_image_url): if debug: print "Starting to create an image regex with urls:\n" + first_image_url + "\n" + second_image_url base = get_string_intersect(first_image_url, second_image_url) baseuri = Uri(base) relativeuri = first_page_uri.MakeRelativeUri(baseuri) if relativeuri.IsAbsoluteUri: domain = relativeuri.Scheme + "://" + relativeuri.Host relative = relativeuri.AbsolutePath else: domain = baseuri.Scheme + "://" + baseuri.Host relative = relativeuri.OriginalString domain = escape_regex_characters(domain) relative = relative.lstrip("/") relative = escape_regex_characters(relative) relative = replace_date_values(relative) domain = Regex.Replace(domain, "www\\\\.", "(?:www\\.)?", RegexOptions.IgnoreCase) baseregex = "(?:" + domain + ")?\\.*/?" + relative if debug: print "baseregex is: " + baseregex regex = "src\\s*=\\s*(?([\"'])[\"'](?<link>" + baseregex + "[^\"']+)[\"']|(?<link>" + baseregex + "[^\\s<>]+))" result, matches = check_created_image_regex(first_image_url, second_image_url, regex) if not result: regex = "(?([\"'])[\"'](?<link>" + baseregex + "[^\"']+)[\"']|(?<link>" + baseregex + "[^\\s<>]+))" result, matches = check_created_image_regex(first_image_url, second_image_url, regex) if not result: #Sometimes the relative link creator makes a bad split, in that case try one other way: #Check if we made the split before: if baseuri.Host == first_page_uri.Host: domain = baseuri.Scheme + "://" + baseuri.Host relative = baseuri.AbsolutePath relative = relative.lstrip("/") domain = escape_regex_characters(domain) relative = escape_regex_characters(relative) relative = replace_date_values(relative) domain = Regex.Replace(domain, "www\\\\.", "(?:www\\.)?", RegexOptions.IgnoreCase) baseregex = "(?:" + domain + ")?\\.*/?" + relative if debug: print "baseregex is: " + baseregex regex = "src\\s*=\\s*(?([\"'])[\"'](?<link>" + baseregex + "[^\"']+)[\"']|(?<link>" + baseregex + "[^\\s<>]+))" result, matches = check_created_image_regex( first_image_url, second_image_url, regex) if not result: regex = "(?([\"'])[\"'](?<link>" + baseregex + "[^\"']+)[\"']|(?<link>" + baseregex + "[^\\s<>]+))" result, matches = check_created_image_regex( first_image_url, second_image_url, regex) if not result: if debug: print "Unable create a working image regex" return None if debug: print "Found a working image regex: " + regex imgregex = ImageRegex(regex) imgregex._matches = matches return imgregex
def FindScanners(worker, books): #Load the various settings. settings is a dict settings = LoadSettings() #Load the scanners unformatedscanners = LoadListFromFile(SCANNERSFILE) #Sort the scanners by length and reverse it. For example cl will come after clickwheel allowing them to be matched correctly. unformatedscanners.sort(key=len, reverse=True) #Format the scanners for use in the regex scanners = "|".join(unformatedscanners) scanners = "(?<Tags>" + scanners + ")" #Load the blacklist and format it blacklist = LoadListFromFile(BLACKLISTFILE) blacklist.extend(LoadUserBlackListFromFile(USERBLACKLISTFILE)) formatedblacklist = "|".join(blacklist) #Add in the blacklist #These amazing regex are designed by the amazing Helmic. pattern = r"(?:(?:__(?!.*__[^_]))|[(\[])(?!(?:" + formatedblacklist + r"|[\s_\-\|/,])+[)\]])(?<Tags>(?=[^()\[\]]*[^()\[\]\W\d_])[^()\[\]]{2,})[)\]]?" replacePattern = r"(?:[^\w]|_|^)(?:" + formatedblacklist + r")(?:[^\w]|_|$)" #Create the regex regex = Regex(pattern, RegexOptions.IgnoreCase) regexScanners = Regex(scanners, RegexOptions.IgnoreCase) regexReplace = Regex(replacePattern, RegexOptions.IgnoreCase) ComicBookFields = ComicRack.App.GetComicFields() ComicBookFields.Remove("Scan Information") ComicBookFields.Add("Language", "LanguageAsText") for book in books: #.net Regex #Note that every possible match is found and then the last one is used. #This is because in some rare cases more than one thing is mistakenly matched and the scanner is almost always the last match. matches = regex.Matches(book.FileName) unknowntag = "" try: match = matches[matches.Count - 1] except ValueError: #No match #print "Trying the Scanners.txt list" #Check the defined scanner names match = regexScanners.Match(book.FileName) #Still no match if match.Success == False: if settings["Unknown"] != "": unknowntag = settings["Unknown"] else: continue #Check if what was grabbed is a field in the comic fields = [] for field in ComicBookFields.Values: fields.append(unicode(getattr(book, field)).lower()) if match.Groups["Tags"].Value.lower() in fields: print "Uh oh. That matched tag is in the info somewhere." newmatch = False for n in reversed(range(0, matches.Count - 1)): if not matches[n].Groups["Tags"].Value.lower() in fields: match = matches[n] newmatch = True break if newmatch == False: if settings["Unknown"] != "": unknowntag = settings["Unknown"] else: continue #Check if the match can be found in () in the series, title or altseries titlefields = [ book.ShadowSeries, book.ShadowTitle, book.AlternateSeries ] abort = False for title in titlefields: titleresult = re.search("\((?P<match>.*)\)", title) if titleresult != None and titleresult.group( "match").lower() == match.Groups["Tags"].Value.lower(): #The match is part of the title, series or altseries so skip it print "The match is part of the title, series or altseries" abort = True break if abort == True: if settings["Unknown"] != "": unknowntag = settings["Unknown"] else: continue #Get a list of the old ScanInformation oldtags = book.ScanInformation ListOfTagsTemp = oldtags.split(",") if '' in ListOfTagsTemp: ListOfTagsTemp.remove('') ListOfTags = [] if ListOfTagsTemp != []: for indtag in ListOfTagsTemp: ListOfTags.append(indtag.strip()) #Create our new tag if unknowntag != "": newtag = settings["Prefix"] + unknowntag else: newtag = settings["Prefix"] + regexReplace.Replace( match.Groups["Tags"].Value.strip("_, "), "") if newtag not in ListOfTags: ListOfTags.append(newtag) #Sort alphabeticaly to be neat ListOfTags.sort() #Add to ScanInformation field book.ScanInformation = ", ".join(ListOfTags)
def regex(self, myString, myVal): regExp = Regex(myVal, RegexOptions.Singleline | RegexOptions.IgnoreCase) return regExp.Match(myString).Success