Example #1
0
 static bool isPalindrome(Match word)
 {
     string wordString = word.ToString();
     for (int i = 0; i < wordString.Length; i++)
     {
         if (wordString[i] != wordString[wordString.Length - i - 1])
         {
             return false;
         }
     }
     return true;
 }
Example #2
0
    private static object ParseDate(Match item, string format)
    {
        try
        {
            DateTime parsedDate = DateTime.ParseExact(item.ToString(), format, null);
            return parsedDate;
        }
        catch (Exception)
        {

            return "Cannot parse";
        }
    }
        public static void TestOccurrencesOf()
        {
            Console.WriteLine();
            Console.WriteLine();
            Match matchResult = FindOccurrenceOf("one two three one two three one two three one"
                                                 + " two three one two three one two three", "two", 2);

            Console.WriteLine($"{matchResult?.ToString()}\t{matchResult?.Index}");

            Console.WriteLine();
            List <Match> results = FindEachOccurrenceOf("one one two three one two three one two" +
                                                        " three one two three", "one", 2);

            foreach (Match m in results)
            {
                Console.WriteLine($"{m.ToString()}\t{m.Index}");
            }
        }
Example #4
0
        public static void TestOccurrencesOf()
        {
            // find second 'two'
            Match matchResult = FindOccurrenceOf(
                "one two three one two three one two three one"
                + " two three one two three one two three",
                "two", 2);

            Console.WriteLine($"{matchResult?.ToString()}\t{matchResult?.Index}");

            Console.WriteLine();

            // find 2, 4, 6, ... 'one'
            List <Match> results = FindEachOccurrenceOf(
                "one two three one two three one two three one"
                + " two three one two three one two three",
                "one", 2);

            foreach (var m in results)
            {
                Console.WriteLine($"{m.ToString()}\t{m.Index}");
            }
        }
Example #5
0
        private static string GetRegexResult(Regex re, string sign, string matchStr)
        {
            Match match = re.Match(matchStr);

            return(re.Replace(match.ToString(), sign));
        }
        private string GetLinkNameVoiceCallAvatar(Match match)
        {
            //UUID agentID = new UUID(match.Groups["agent_id"].Value);

            return(match.ToString());
        }
        /// <summary>
        /// Gets the display text for the specified URI
        /// </summary>
        /// <param name="uri">URI to get the display text of</param>
        /// <returns>Display text for URI</returns>
        public string GetLinkName(string uri)
        {
            if (!RadegastInstance.GlobalInstance.GlobalSettings["resolve_uris"])
            {
                return(uri);
            }

            Match match = patternUri.Match(uri);

            if (!match.Success)
            {
                return(uri);
            }

            // Custom named links in the form of [secondlife://<truncated> Custom%20Link%20Name] will
            //   result in a link named 'Custom Link Name' regardless of the previous secondlife URI.
            if (match.Groups["startingbrace"].Success && match.Groups["endingbrace"].Length > 0)
            {
                return(HttpUtility.UrlDecode(match.Groups["endingbrace"].Value));
            }

            if (match.Groups["regionuri"].Success)
            {
                return(GetLinkNameRegionUri(match));
            }

            if (match.Groups["appuri"].Success)
            {
                string appcommand = match.Groups["appcommand"].Value;

                switch (appcommand)
                {
                case "agent":
                    return(GetLinkNameAgent(match));

                case "appearance":
                    return(match.ToString());

                case "balance":
                    return(match.ToString());

                case "chat":
                    return(GetLinkNameChat(match));

                case "classified":
                    return(GetLinkNameClassified(match));

                case "event":
                    return(GetLinkNameEvent(match));

                case "group":
                    return(GetLinkNameGroup(match));

                case "help":
                    return(GetLinkNameHelp(match));

                case "inventory":
                    return(GetLinkNameInventory(match));

                case "maptrackavatar":
                    return(GetLinkNameTrackAvatar(match));

                case "objectim":
                    return(GetLinkNameObjectIm(match));

                case "parcel":
                    return(GetLinkNameParcel(match));

                case "search":
                    return(GetLinkNameSearch(match));

                case "sharewithavatar":
                    return(GetLinkNameShareWithAvatar(match));

                case "teleport":
                    return(GetLinkNameTeleport(match));

                case "voicecallavatar":
                    return(GetLinkNameVoiceCallAvatar(match));

                case "wear_folder":
                    return(GetLinkNameWearFolder(match));

                case "worldmap":
                    return(GetLinkNameWorldMap(match));

                default:
                    return(match.ToString());
                }
            }

            return(match.ToString());
        }
        private string GetLinkNameClassified(Match match)
        {
            //UUID classifiedID = new UUID(match.Groups["classified_id"].Value);

            return(match.ToString());
        }
        private string GetLinkNameHelp(Match match)
        {
            //string helpQuery = HttpUtility.UrlDecode(match.Groups["help_query"].Value);

            return(match.ToString());
        }
        /// <summary>
        /// VRChatのログを解析します。
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private List <ActivityLog> ParseVRChatLog(string filePath)
        {
            var    logger       = Logger.GetLogger();
            string rawData      = "";
            var    activityLogs = new List <ActivityLog>();

            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (var sr = new StreamReader(fs, Encoding.GetEncoding("UTF-8")))
                {
                    while ((rawData = sr.ReadLine()) != null)
                    {
                        if (rawData.Length > 25 && rawData.Substring(20, 5) == "Error")
                        {
                            continue;
                        }
                        Match match = RegexPatterns.All.Match(rawData);
                        if (match.Groups[PatternType.ReceivedInvite].Value.Length != 0)
                        {
                            var m                    = RegexPatterns.ReceivedInviteDetail.Match(match.ToString());
                            var jsonRawData          = m.Groups[2].Value.Replace("{{", "{").Replace("}}", "}");
                            var numCurlyBracketBegin = jsonRawData.Count(c => c == '{');
                            var numCurlyBracketEnd   = jsonRawData.Count(c => c == '}');
                            if (numCurlyBracketBegin > numCurlyBracketEnd)
                            {
                                jsonRawData += new string('}', numCurlyBracketBegin - numCurlyBracketEnd);
                            }
                            dynamic content     = JsonConvert.DeserializeObject(jsonRawData);
                            var     activityLog = new ActivityLog
                            {
                                ActivityType   = ActivityType.ReceivedInvite,
                                Timestamp      = DateTime.Parse(m.Groups[1].Value),
                                NotificationID = content.id,
                                UserID         = content.senderUserId,
                                UserName       = content.senderUsername,
                                WorldID        = content.details.worldId,
                                WorldName      = content.details.worldName,
                            };
                            if (!activityLogs.Where(a => a.NotificationID == activityLog.NotificationID).Any())
                            {
                                activityLogs.Add(activityLog);
                            }
                            continue;
                        }
                        if (match.Groups[PatternType.ReceivedRequestInvite].Value.Length != 0)
                        {
                            var     m           = RegexPatterns.ReceivedRequestInviteDetail.Match(match.ToString());
                            var     jsonRawData = m.Groups[2].Value.Replace("{{", "{").Replace("}}", "}");
                            dynamic content     = JsonConvert.DeserializeObject(jsonRawData);
                            var     activityLog = new ActivityLog
                            {
                                ActivityType   = ActivityType.ReceivedRequestInvite,
                                Timestamp      = DateTime.Parse(m.Groups[1].Value),
                                NotificationID = content.id,
                                UserID         = content.senderUserId,
                                UserName       = content.senderUsername,
                            };
                            if (!activityLogs.Where(a => a.NotificationID == activityLog.NotificationID).Any())
                            {
                                activityLogs.Add(activityLog);
                            }
                            continue;
                        }
                        if (match.Groups[PatternType.SendInvite].Value.Length != 0)
                        {
                            var m = RegexPatterns.SendInviteDetail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType = ActivityType.SendInvite,
                                Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                UserID       = m.Groups[2].Value,
                                WorldID      = m.Groups[3].Value,
                                WorldName    = m.Groups[4].Value,
                            });
                            continue;
                        }
                        if (match.Groups[PatternType.SendRequestInvite].Value.Length != 0)
                        {
                            var m = RegexPatterns.SendRequestInviteDetail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType = ActivityType.SendRequestInvite,
                                Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                UserID       = m.Groups[2].Value,
                            });
                            continue;
                        }
                        if (match.Groups[PatternType.JoinedRoom1].Value.Length != 0)
                        {
                            var m = RegexPatterns.JoinedRoom1Detail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType = ActivityType.JoinedRoom,
                                Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                WorldID      = m.Groups[2].Value,
                            });
                            continue;
                        }
                        if (match.Groups[PatternType.JoinedRoom2].Value.Length != 0)
                        {
                            var m = RegexPatterns.JoinedRoom2Detail.Match(match.ToString());
                            if (activityLogs.Any() && activityLogs[activityLogs.Count - 1].ActivityType == ActivityType.JoinedRoom)
                            {
                                activityLogs[activityLogs.Count - 1].WorldName = m.Groups[2].Value;
                            }
                            else
                            {
                                activityLogs.Add(new ActivityLog
                                {
                                    ActivityType = ActivityType.JoinedRoom,
                                    Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                    WorldName    = m.Groups[2].Value,
                                });
                            }
                            continue;
                        }
                        if (match.Groups[PatternType.MetPlayer].Value.Length != 0)
                        {
                            var m = RegexPatterns.MetPlayerDetail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType = ActivityType.MetPlayer,
                                Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                UserName     = m.Groups[2].Value,
                            });
                            continue;
                        }
                        if (match.Groups[PatternType.SendFriendRequest].Value.Length != 0)
                        {
                            var m = RegexPatterns.SendFriendRequestDetail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType = ActivityType.SendFriendRequest,
                                Timestamp    = DateTime.Parse(m.Groups[1].Value),
                                UserID       = m.Groups[2].Value,
                            });
                            continue;
                        }
                        if (match.Groups[PatternType.ReceivedFriendRequest].Value.Length != 0)
                        {
                            var     m           = RegexPatterns.ReceivedFriendRequestDetail.Match(match.ToString());
                            var     jsonRawData = m.Groups[2].Value.Replace("{{", "{").Replace("}}", "}");
                            dynamic content     = JsonConvert.DeserializeObject(jsonRawData);
                            var     activityLog = new ActivityLog
                            {
                                ActivityType   = ActivityType.ReceivedFriendRequest,
                                Timestamp      = DateTime.Parse(m.Groups[1].Value),
                                NotificationID = content.id,
                                UserID         = content.senderUserId,
                                UserName       = content.senderUsername,
                            };
                            if (!activityLogs.Where(a => a.NotificationID == activityLog.NotificationID).Any())
                            {
                                activityLogs.Add(activityLog);
                            }
                            continue;
                        }
                        if (match.Groups[PatternType.AcceptFriendRequest].Value.Length != 0)
                        {
                            var m = RegexPatterns.AcceptFriendRequestDetail.Match(match.ToString());
                            activityLogs.Add(new ActivityLog
                            {
                                ActivityType   = ActivityType.AcceptFriendRequest,
                                Timestamp      = DateTime.Parse(m.Groups[1].Value),
                                UserName       = m.Groups[2].Value,
                                UserID         = m.Groups[3].Value,
                                NotificationID = m.Groups[4].Value,
                            });
                            continue;
                        }
                    }
                }

            return(activityLogs);
        }
Example #11
0
        public void ShouldConvertToGrammarString()
        {
            var expr = new Match(new LiteralTerminal("a"));

            Assert.Equal("&'a'", expr.ToString());
        }
Example #12
0
 static string dotToDash(Match m)
 {
     string x = m.ToString();
     return x.Replace(@".", @"_");
 }
        private string VariableReplacer(Match match)
        {
            string returnValue;
            if (varStorage.TryGetValue(match.ToString().Substring(1, match.Length - 2), out returnValue))
            {
                return returnValue;
            }

            return "";
        }
Example #14
0
 //replace "0A" (in \x0A) into '\n'
 private string _replaceEscapeSequenceToChar(Match foundEscapeSequence)
 {
     char[] hexValues = new char[2];
     //string hexChars = foundEscapeSequence.Value.ToString();
     string matchedEscape = foundEscapeSequence.ToString();
     hexValues[0] = matchedEscape[2];
     hexValues[1] = matchedEscape[3];
     string hexValueString = new string(hexValues);
     int convertedInt = int.Parse(hexValueString, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo);
     char hexChar = Convert.ToChar(convertedInt);
     string hexStr = hexChar.ToString();
     return hexStr;
 }
    public override void ProcessRequest(HttpContext context, Match match)
    {
        //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //context.Response.Cache.SetMaxAge(TimeSpan.FromHours(24));

        // Environmental Setup
        PccConfig.LoadConfig("pcc.config");
        imagePath = PccConfig.ImageStampFolder;

        try
        {
            string imageFormat = context.Request.QueryString["format"];
            char[] charsToTrim = { '/', '\\' };
            string[] paramslist = match.ToString().Split(charsToTrim);
            string[] validParams = new[] { "base64", "image" };
            String imageStampId = String.Empty;

            var flag = Array.Exists(validParams, element => element == imageFormat.ToLower());

            if (flag)
            {
                imageStampId = paramslist[2];
                imageStampPath = GetPath(imageStampId);

                String fileExtension = Path.GetExtension(imageStampPath);

                this.ValidateImagefileType(imageStampId);

                if (imageFormat.ToLower() == "base64")
                {
                    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    context.Response.Cache.SetMaxAge(TimeSpan.FromHours(24));

                    context.Response.ContentType = "text/plain";
                    context.Response.Write(ImageToBase64String(imageStampId));
                }
                if (imageFormat.ToLower() == "image")
                {
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    context.Response.Cache.SetMaxAge(TimeSpan.FromHours(24));
                    context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
                    context.Response.ClearHeaders();
                    context.Response.ContentType = GetMimeType(fileExtension);
                    context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(imageStampPath).ToString());
                    context.Response.WriteFile(imageStampPath);
                }
            }
            else
            {
                throw new Exception("Parameter format requires valid values. Valid values are Base64 and Image");
            }
        }
        catch (Exception e)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.Write("Exception Message: " + e.Message);
            context.Response.Write("StackTrace: " + e.StackTrace.ToString());
            //context.Response.Write("Exception InnerException: " + e.InnerException.ToString());
            context.Response.ContentType = "text/plain";
            return;
        }

        context.Response.StatusCode = (int)HttpStatusCode.OK;
    }
Example #16
0
 /// <summary>
 /// Called to evaluate the HTML fragment corresponding to each 
 /// matching token in the code.
 /// </summary>
 /// <param name="match">The <see cref="Match"/> resulting from a 
 /// single regular expression match.</param>
 /// <returns>A string containing the HTML code fragment.</returns>
 protected override string MatchEval(Match match)
 {
     if (match.Groups[1].Success) //comment
     {
         var reader = new StringReader(match.ToString());
         string line;
         var sb = new StringBuilder();
         while ((line = reader.ReadLine()) != null)
         {
             if (sb.Length > 0)
             {
                 sb.Append("\n");
             }
             sb.Append("<span class=\"rem\">");
             sb.Append(line);
             sb.Append("</span>");
         }
         return sb.ToString();
     }
     if (match.Groups[2].Success) //string literal
     {
         return "<span class=\"str\">" + match.ToString() + "</span>";
     }
     if (match.Groups[3].Success) //preprocessor keyword
     {
         return "<span class=\"preproc\">" + match.ToString() + "</span>";
     }
     if (match.Groups[4].Success) //keyword
     {
         return "<span class=\"kwrd\">" + match.ToString() + "</span>";
     }
     System.Diagnostics.Debug.Assert(false, "None of the above!");
     return ""; //none of the above
 }
 public static string Rep1(Match input)
 {
     if (string.Compare(input.ToString(), "Big", StringComparison.CurrentCultureIgnoreCase) == 0)
         return "Huge";
     else
         return "Tiny";
 }
Example #18
0
 private static string URL(Match m)
 {
     string x = m.ToString();
     return x.Link(x);
 }
Example #19
0
        public static bool TryMGRS(string ns, out string[] mgrs)
        {
            //Prepare string for regex validation
            string s = ns.Replace(" ", "").ToUpper();

            if (Regex.IsMatch(s, @"[0-9]{1,2}[a-z,A-Z]{3}\d+ME\d+MN"))
            {
                int         found = 0;
                List <char> msc   = new List <char>();
                foreach (var c in s.ToArray())
                {
                    bool isLetter = char.IsLetter(c);
                    if (isLetter)
                    {
                        found++;
                    }

                    if (found > 3 && isLetter)
                    {
                        continue;
                    }
                    msc.Add(c);
                }
                s = string.Join("", msc);
            }

            mgrs = null;
            //Add easting northing at 0,0 if not provided


            //Attempt Regex Match
            Regex regex = new Regex(@"[0-9]{1,2}[a-z,A-Z]{3}\d+");

            //Add default easting/northing if not provided
            if (!regex.Match(s).Success&& regex.Match(s + "00").Success)
            {
                s += "00";
            }

            Match match = regex.Match(s);

            if (match.Success && match.ToString().Trim() == s)
            {
                //Extract Numbers for one string MGRS
                regex = new Regex("\\d+");
                MatchCollection matches = regex.Matches(s);

                //IF character count of Easting Northing aren't even return false as precision is unknown.
                int splitSpot = matches[1].Value.Count();
                if (splitSpot % 2 == 0)
                {
                    string longZone        = matches[0].Value;
                    string eastingNorthing = matches[1].Value;

                    //Extract Letters

                    regex   = new Regex("[a-z,A-Z]");
                    matches = regex.Matches(s);
                    string latZone    = matches[0].Value;
                    string identifier = matches[1].Value + matches[2].Value;

                    //Split Easting and Northing Values
                    string easting  = eastingNorthing.Substring(0, (int)(eastingNorthing.Length / 2));
                    string northing = eastingNorthing.Substring((int)(eastingNorthing.Length / 2), (int)(eastingNorthing.Length / 2));

                    mgrs = new string[] { longZone, latZone, identifier, easting.PadRight(5, '0'), northing.PadRight(5, '0') };
                    return(true);
                }
            }

            return(false);
        }
Example #20
0
        static void Main(string[] args)
        {/*
          * //spr czy uż wprowadził poprawny adres email
          * Regex regEmail = new Regex(@"^[a-z][a-z0-9_]*@[a-z0-9]*\.[a-z]{2,3}$");
          * Console.WriteLine("Podaj email");
          * string napis = Console.ReadLine();
          * Console.WriteLine("Podany adres: {0} to {1}poprawny adres email", napis, regEmail.IsMatch(napis)?"":"nie");
          *
          * //w dłuższym pierwszym tekscie szuka dopasowania do drugiego
          * Match m = Regex.Match("Dowolny ulubiony kolor", @"kolor?");
          * Console.WriteLine(m.ToString()); //WYPISZE: kolor
          *
          * //Za pomocą metody NextMatch() można zwrócić kolejne dopasowania
          * Match m1 = Regex.Match("Tylko jeden kolor? Mam na myśli dwa kolory!",@"kolory?");
          * Match m2 = m1.NextMatch();
          * Console.WriteLine(m1); // kolor
          * Console.WriteLine(m2); // kolory
          *
          * //Metoda Matches() zwraca wszystkie dopasowania w postaci tablicy.
          * foreach (Match ms in Regex.Matches("Tylko jeden kolor? Mam na myśli dwa kolory !", @"kolory?"))
          *     Console.WriteLine("Matches: "+ms); //zwróci kolor, kolory
          *
          *
          * //często używanym operatorem w wyr regularnych jest alternatywa(|). Poniższe polecenie powoduje dopasowanie imion Karol i Karolina:
          * //Nawiasy wokół alternatywy pozwalają na oddzielenie alternatyw od pozostałej części wyrażenia
          * Console.WriteLine(Regex.IsMatch("Ka", "Kar(ol|olina)?")); // prawda
          * //? odnosi sie do wszystkich znaków w nawiasie, Gdyby nie było nawiasu to odnosi sie tylko do ostatniego znaku przed
          *
          * //?
          * Console.WriteLine("Sprawdzenie jak działa ? ");
          * Regex wyrazenie = new Regex(@"pomidory?");
          * string testAsi = "pom";
          * bool odp=wyrazenie.IsMatch(testAsi);
          * Console.WriteLine("wynik mojego testu={0}",odp); //false
          * string testAsi2 = "pomidor";
          * bool odp2 = wyrazenie.IsMatch(testAsi2);
          * Console.WriteLine("wynik mojego testu={0}", odp2); //true
          * string testAsi3 = "pomidory";
          * bool odp3 = wyrazenie.IsMatch(testAsi3);
          * Console.WriteLine("wynik mojego testu={0}", odp3); //true
          *
          * //Kompilowane wyrażenia regularne
          * Console.WriteLine("spr Kompilowane wyrażenia regularne");
          * Regex wyr = new Regex(@"pomidory?",RegexOptions.Compiled);
          * Console.WriteLine(wyr.Match("pomidor")); //Match ma 2 argumenty pierwszy to ciąg znaków w którym szukamy, drugi to czego szukamy
          * Console.WriteLine(wyr.Match("pomidory"));
          *
          * //walidacja url i zapis do listy
          *     Console.WriteLine("QUESTION68");
          *     //string url = "https://www.google.com";
          *     string url = "http://www.google.com";
          *     const string pattern = @"http://(www\.)?([^\.]+)\.com";
          *     List<string> result = new List<string>();
          *     MatchCollection myMatches = Regex.Matches(url, pattern);
          *
          *     foreach (Match currentMatch in myMatches)
          *     {
          *         result.Add(currentMatch.Value);
          *     }
          *
          *     foreach (string wynik in result)
          *     {
          *         Console.WriteLine("wynik: " + wynik);
          *     }
          *
          * //walidacja nr tel
          * Console.WriteLine("QUESTION78");
          * string input = "789-456-123";
          *     //string pattern = @"[0-9][0-9][0-9]\-[0-9][0-9][0-9]\-[0-9][0-9][0-9]";
          *     //string pattern = @"[0-9]*\-[0-9]*\-[0-9]*";
          *     string wzorTelefonu = @"[0-9]{3}\-[0-9]{3}\-[0-9]{3}"; //{3}-trzy wystąpienia
          *     Match mat = Regex.Match(input, wzorTelefonu);
          *     Console.WriteLine(mat.ToString());
          */
            //walidacja ceny, żeby była dodatnia oraz z 2 miejscami po przecinku
            Console.WriteLine("QUESTION155");
            string cena0  = "6.55";
            string cena1  = "-6.55";
            double cena2  = 6;
            string cena22 = cena2.ToString();
            double cena3  = -6;
            string cena33 = (-6).ToString();
            double cena4  = -6.55;
            double cena5  = 6.556;
            //string wzorCeny = @"^(-)?\d+(\.\d\d)?"; //cały nawias odwołuje się do ?
            string wzorCeny = @"^\d+(\.\d\d)?";
            Match  ma0      = Regex.Match(cena0, wzorCeny);

            Console.WriteLine(ma0.ToString());

            Match ma1 = Regex.Match(cena1, wzorCeny);

            Console.WriteLine(ma1.ToString());

            Match ma2 = Regex.Match(cena22, wzorCeny);

            Console.WriteLine(ma2.ToString());

            Match ma3 = Regex.Match(cena33, wzorCeny);

            Console.WriteLine(ma3.ToString());

            Match ma4 = Regex.Match(cena4.ToString(), wzorCeny);

            Console.WriteLine(ma4.ToString());

            Match ma5 = Regex.Match(cena5.ToString(), wzorCeny);

            Console.WriteLine(ma5.ToString());

            Regex wy5 = new Regex(wzorCeny, RegexOptions.Compiled);

            Console.WriteLine(wy5.Match(cena5.ToString()));


            Console.ReadKey();

            /*
             * . Dowolny znak oprócz znaku nowego wiersza
             * ^ Początek wiersza
             * $ Koniec wiersza
             * Zero lub więcej wystąpień danego zestawu znaków (wyrażeń)
             * ? Zero lub jedno wystąpienie danego zestawu znaków
             + Jedno lub więcej wystąpień danego zestawu znaków
             + [a-c] Dowolny znak ze zbioru znajdującego się wewnątrz nawiasów kwadratowych
             + [^ ab] Wszystkie znaki oprócz tych z zestawu znajdujących się wewnątrz nawiasów kwadratowych
             | Lub
             | {x} Dokładnie X wystąpień danego zestawu znaków (wyrażeń)
             | {x,} Co najmniej X wystąpień danego zestawu znaków (wyrażeń)
             | {x,y} Co najmniej X wystąpień i maksymalnie Y wystąpień danego zestawu znaków
             | \d Cyfra
             | \znak Oznacza ten znak
             | a|b Alternatywa — a lub b
             | \b Granica słowa
             | \n Nowa linia
             */
        }
Example #21
0
        public static string MatchReplacer(Match ma)
        {
            string s = ma.ToString();

            s = s.Substring(2, s.Length - 4).Trim();
            string ret = "";

            switch (s)
            {
            case "cppLibName":
                return("lib" + basePackageName + ".messages.so");

            case "subscriptionDelegateTypes":
                foreach (Message m in msgList)
                {
                    ret += "public delegate void On" + m.BaseName + "(" + m.CsClassName + " m);\n";
                }
                return(ret);

            case "subscriptionMethods":
                foreach (Message m in msgList)
                {
                    ret += "public void Subscribe(string topic,On" + m.BaseName + " callback, int queueSize) {\n";
                    ret += "\t" + m.CsNameSpace + ".Subscriber" + m.BaseName + " sub=null;\n";
                    ret += "\tif(this." + m.BaseName + "Subscribers.TryGetValue(topic,out sub)) {\n";
                    ret += "\t\tsub.Add(callback);\n";
                    ret += "\t} else {\n";
                    ret += "\t\tsub = new " + m.CsNameSpace + ".Subscriber" + m.BaseName + "(this.node, topic,callback,queueSize);\n";
                    ret += "\t\tthis." + m.BaseName + "Subscribers.Add(topic,sub);\n";
                    ret += "\t}\n";
                    ret += "}\n";
                    ret += "public void Subscribe(string topic,On" + m.BaseName + " callback) {\n";
                    ret += "\tthis.Subscribe(topic,callback,1);\n";
                    ret += "}\n";
                }
                return(ret);

            case "unsubscriptionMethods":
                foreach (Message m in msgList)
                {
                    ret += "public void UnSubscribe(string topic,On" + m.BaseName + " callback) {\n";
                    ret += "\t" + m.CsNameSpace + ".Subscriber" + m.BaseName + " sub=null;\n";
                    ret += "\tif(this." + m.BaseName + "Subscribers.TryGetValue(topic,out sub)) {\n";
                    ret += "\t\tsub.Remove(callback);\n";
                    ret += "\t\tif(sub.IsEmpty()) {\n";
                    ret += "\t\t\tthis." + m.BaseName + "Subscribers.Remove(topic);\n";
                    ret += "\t\t\tsub.Close();\n";
                    ret += "\t\t}\n";
                    ret += "\t}\n";
                    ret += "}\n";
                }
                return(ret);

            case "subscriberClosingCalls":
                foreach (Message m in msgList)
                {
                    ret += "\tforeach(" + m.CsNameSpace + ".Subscriber" + m.BaseName + " sub in this." + m.BaseName + "Subscribers.Values) {\n";
                    ret += "\t\tsub.Close();\n";
                    ret += "\t}\n";
                    ret += "\tthis." + m.BaseName + "Subscribers.Clear();\n";
                }
                return(ret);

            case "sendMethods":
                foreach (Message m in msgList)
                {
                    ret += "public void Send(IntPtr pub," + m.CsClassName + " msg) {\n";
                    ret += "\tint len = msg.GetSize();\n";
                    ret += "\tIntPtr p = Marshal.AllocHGlobal(len);\n";
                    ret += "\ttry {\n";
                    ret += "\t\tmsg.GetData(p);\n";
                    ret += "\t\tSendMessage(pub," + m.Id + ",p);\n";
                    ret += "\t}\n";
                    ret += "\tcatch(Exception e) { Console.Error.WriteLine(\"Error while sending: \"+e); }\n";
                    ret += "\tfinally { Marshal.FreeHGlobal(p); }\n";
                    ret += "}\n";
                }
                return(ret);

            case "subscriberStructures":
                foreach (Message m in msgList)
                {
                    ret += "protected Dictionary<string," + m.CsNameSpace + ".Subscriber" + m.BaseName + "> " + m.BaseName + "Subscribers = new Dictionary<string," + m.CsNameSpace + ".Subscriber" + m.BaseName + ">();\n";
                }
                return(ret);

            case "m.CsNameSpace":
                return(curMessage.CsNameSpace);

            case "m.CsBaseClassName":
                return(curMessage.BaseName);

            case "m.FullCsClassName":
                return(curMessage.CsClassName);

            case "m.Id":
                return(curMessage.Id.ToString());

            case "m.FullName":
                return(curMessage.FullName);

            case "m.SubscriptionDelegateType":
                return("public delegate void On" + curMessage.BaseName + "(" + curMessage.CsClassName + " m);\n");

            case "cppSubscriptionMethods":
                ret += "extern \"C\" void subscribe(ros::NodeHandle* node, char* topic, uint64_t messageId, void (*handle)(char*),int queueSize, void** subscriberPtr) {\n";
                ret += "\tswitch(messageId) {\n";
                foreach (Message m in msgList)
                {
                    ret += "\t\tcase " + m.Id + "ull:\n";
                    //ret += "\t\tRosCs::CsSubscriber<"+m.RosClassName+">(handle,translate).SubscribeAndListen(node,topic,queueSize);\n";
                    //ret+= "\t\tRosCs::CsSubscriber<"+m.RosClassName+"> csub = RosCs::CsSubscriber<"+m.RosClassName+">(handle,translate);\n";
                    ret += "\t\t{ RosCs::CsSubscriber<" + m.RosClassName + "> sub" + m.Id + "(handle,translate);\n";
                    ret += "\t\t*subscriberPtr = (void*) &sub" + m.Id + ";\n";
                    ret += "\t\tsub" + m.Id + ".SubscribeAndListen(node,topic,queueSize);}\n";
                    ret += "\t\tbreak;\n";
                }
                ret += "\t\tdefault: std::cerr<<\"Unknown message id: \"<< messageId << std::endl;\n";
                ret += "\t}\n";
                ret += "}\n";
                return(ret);

            case "cppSendBody":
                foreach (Message m in msgList)
                {
                    ret += "\tcase " + m.Id + "ull: {\n";
                    ret += "\t\t" + m.RosClassName + " m" + m.Id + " = " + m.RosClassName + "();\n";
                    ret += "\t\ttranslate2Ros(data,m" + m.Id + ");\n";
                    ret += "\t\tpub->publish<" + m.RosClassName + ">(m" + m.Id + ");\n";
                    ret += "\t\t} break;\n";
                }
                return(ret);

            case "cppMessageHandleMethods":
                foreach (Message m in msgList)
                {
                    ret += "char* translate(const " + m.RosClassName + "::ConstPtr& m) {\n";
                    //ret+= "uint32_t size = getSizeOf(m);\n";
                    ret += "uint32_t size = getSizeOf(*m);\n";
                    //ret+= "std::cout << \"Ros2Cpp message size: \"<< size << std::endl;\n";
                    ret += "char* ret = (char*)malloc(size);\n";
                    //ret+= "int32_t* intp = (int*) ret;\n";
                    Message.PointersUsed.Clear();
                    Message.Mode = Message.GEN_CPP;
                    ret         += m.PointerDeclaration();
                    foreach (string type in m.BaseTypes())
                    {
                        Message.PointersUsed.Add(type, type + "p");
                    }
                    //Message.PointersUsed.Add("int32","intp");
                    string ptrType = "";                    //"int32";
                    string ptrName = "ret";
                    ret += CleanLastLine(m.Ros2Char("m->", ref ptrType, ref ptrName, 0));
                    ret += "\treturn ret;\n";
                    ret += "}\n";
                }
                return(ret);

            case "cppArray2RosMethods":
                foreach (Message m in msgList)
                {
                    ret += "void translate2Ros(int32_t* p, " + m.RosClassName + "& m) {\n";
                    Message.PointersUsed.Clear();
                    Message.Mode = Message.GEN_CPP;
                    Message.PointersUsed.Add("int32", "p");
                    //string decl = m.PointerDeclaration();

                    ret += m.PointerDeclaration("int32");
                    foreach (string type in m.BaseTypes())
                    {
                        if (!type.Equals("int32"))
                        {
                            Message.PointersUsed.Add(type, type + "p");
                        }
                    }

                    string ptrType = "int32";
                    string ptrName = "p";
                    ret += CleanLastLine(m.Char2Ros("m.", ref ptrType, ref ptrName, 0));
                    ret += "}\n";
                }
                return(ret);

            case "cppMakePublisher":
                ret += "\tswitch(messageId) {\n";
                foreach (Message m in msgList)
                {
                    ret += "\t\tcase " + m.Id + "ull:\n";
                    ret += "\t\ttmp=node->advertise<" + m.RosClassName + ">(topic,queueSize,false);\n";
                    ret += "\t\tbreak;\n";
                }
                ret += "\t\tdefault: std::cerr<<\"Unknown messageId: \"<<messageId<<std::endl;\n";
                ret += "\t}\n";
                return(ret);

            case "cppGetSizeOfMessage":
                foreach (Message m in msgList)
                {
                    //ret+= "uint32_t getSizeOf(const "+m.RosClassName+"::ConstPtr& m);\n";
                    ret += "uint32_t getSizeOf(const " + m.RosClassName + "& m);\n";
                }
                ret += "\n";
                foreach (Message m in msgList)
                {
                    ret += "uint32_t getSizeOf(const " + m.RosClassName + "& m) {\n";
                    //ret+= "uint32_t getSizeOf(const "+m.RosClassName+"::ConstPtr& m) {\n";
                    ret += m.GetCPPSizeBody();
                    ret += "}\n";
                }
                return(ret);

            case "messageIncludes":
                foreach (Message m in msgList)
                {
                    ret += "#include \"" + m.FullName + ".h\"\n";
                }
                return(ret);

            default: Console.Error.WriteLine("Unknown Marker: {0}", s);
                System.Environment.Exit(-1);
                break;
            }
            return(ret);
        }
        public string crawler(string uri)
        {
            ArrayList albumInfoArray = new ArrayList();

            albumInfoArray.Clear();
            Console.Out.WriteLine(uri);
            int previousTrack = 0;

            try
            {
                // Create a request for the URL.
                WebRequest request = WebRequest.Create(uri);
                // If required by the server, set the credentials.
                request.Credentials = CredentialCache.DefaultCredentials;
                // Get the response.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // Display the status.
                //Console.WriteLine(response.StatusDescription);
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                //Console.WriteLine(responseFromServer);
                // Cleanup the streams and the response.
                string[] songInfo;
                string   knife01 = "曲目列表</span></h2>";
                string   knife02 = "评论</span></h2>";
                string   tuneInfo;
                try
                {
                    tuneInfo = cutStrings(responseFromServer, knife01, knife02)[0];

                    Regex knifeForSong = new Regex("<tr><td id=\"\\d{0,3}\" class=\"info\\w{1,3}\"><b>");
                    songInfo = knifeForSong.Split(tuneInfo);
                }
                catch (Exception)
                {
                    tuneInfo = cutStrings(responseFromServer, knife01, 0);

                    Regex knifeForSong = new Regex("<tr><td id=\"\\d{0,3}\" class=\"info\\w{1,3}\"><b>");
                    songInfo = knifeForSong.Split(tuneInfo);
                }

                //Console.Out.WriteLine("1234567890".Remove(0,5));
                foreach (string s in songInfo)
                {
                    bool      isTurn         = true;
                    bool      isOrigin       = true;
                    bool      isArtist       = true;
                    bool      isOnlyComposer = false;
                    bool      isVoice        = false;
                    string    tune           = s;
                    int       trackInt       = 0;
                    string    title          = "";
                    string    artist         = "";
                    string    arrange        = "";
                    string    composer       = "";
                    string    voice          = "";
                    ArrayList origin         = new ArrayList();

                    //track
                    Regex  trackReg    = new Regex(@"^\d{1,3}");
                    string trackString = trackReg.Match(tune).ToString();
                    try
                    {
                        trackInt = int.Parse(trackString);
                        Console.Out.WriteLine("轨道:" + trackInt);
                    }
                    catch (Exception)
                    {
                        Console.Out.WriteLine("没有获取到序号");
                        isTurn = false;
                    }

                    //title
                    try
                    {
                        tune  = cutStrings(tune, "<td", 0);
                        title = cutStrings(tune, "", "</td>")[0];

                        Regex cut        = new Regex(">[^<]{1,}<");
                        Match titleMatch = cut.Match(title);
                        title = titleMatch.ToString();
                        title = cutStrings(title, ">", "<", 1, 0)[0];
                        //{
                        //    string[] lsSs = cutString(tune, "action=edit\">", "</a>", 13, 0);
                        //    title = lsSs[0];
                        //    tune = lsSs[1];
                        //}
                        //else
                        //{
                        //    string[] lsSs = cutString(tune, "class=\"title\">", "<span class", 14, 0);
                        //    title = lsSs[0];
                        //    tune = lsSs[1];
                        //}
                        Console.Out.WriteLine("曲名:" + title);
                    }
                    catch (Exception)
                    {
                        Console.Out.WriteLine("没有获取到标题");
                        isTurn = false;
                    }
                    if (isTurn)
                    {
                        if (Regex.IsMatch(tune, "配音"))
                        {
                            tune  = cutStrings(tune, "配音", 0);
                            voice = cutStrings(tune, "", "</td></tr>")[0];
                            tune  = cutStrings(tune, "配音", "</td></tr>")[1];
                            voice = cutTags(voice);
                            voice = voice.Replace("(页面不存在)", "");
                            Console.Out.WriteLine("配音:" + voice);
                            string ls = "";
                            for (; Regex.IsMatch(voice, "("); ls += ";")
                            {
                                ls   += cutStrings(voice, "(", ")", 1, 0)[0];
                                voice = cutStrings(voice, ")", 1);
                                Console.Out.WriteLine(voice);
                            }
                            voice   = ls;
                            voice   = voice.Remove(voice.Length - 1);
                            isVoice = true;
                        }
                        else if (Regex.IsMatch(tune, "演唱"))
                        {
                            tune   = cutStrings(tune, "演唱", 0);
                            artist = cutStrings(tune, "", "</td></tr>")[0];
                            tune   = cutStrings(tune, "演唱", "</td></tr>")[1];
                            artist = cutTags(artist);
                            artist = artist.Replace("(页面不存在)", "");
                            Console.Out.WriteLine("演唱:" + artist);
                        }
                        else if (Regex.IsMatch(tune, "编曲"))
                        {
                            tune    = cutStrings(tune, "编曲", 0);
                            arrange = cutStrings(tune, "", "</td></tr>")[0];
                            tune    = cutStrings(tune, "编曲", "</td></tr>")[1];
                            arrange = cutTags(arrange);
                            arrange = arrange.Replace("(页面不存在)", "");
                            Console.Out.WriteLine("编曲:" + arrange);
                            isArtist = false;
                        }
                        else if (Regex.IsMatch(tune, "作曲"))
                        {
                            tune     = cutStrings(tune, "作曲", 0);
                            composer = cutStrings(tune, "", "</td></tr>")[0];
                            tune     = cutStrings(tune, "作曲", "</td></tr>")[1];
                            composer = cutTags(composer);
                            composer = composer.Replace("(页面不存在)", "");
                            Console.Out.WriteLine("作曲:" + composer);
                            isArtist       = false;
                            isOnlyComposer = true;
                        }
                        if (Regex.IsMatch(tune, "原曲"))
                        {
                            Console.Out.WriteLine("原曲:");
                            for (; Regex.IsMatch(tune, "ogmusic");)
                            {
                                tune = cutStrings(tune, "ogmusic", 0);
                                tune = cutStrings(tune, "title=\"", 7);
                                string onriginTurn = Regex.Split(tune, "\">")[0];
                                origin.Add(onriginTurn);
                                Console.Out.WriteLine(onriginTurn);
                            }
                        }
                        else
                        {
                            isOrigin = false;
                        }
                    }

                    Console.Out.WriteLine("next\n");

                    if (isTurn)
                    {
                        if (previousTrack > trackInt)
                        {
                            tune = "\r\n\r\n\r\n";
                        }
                        else
                        {
                            tune = "";
                        }
                        if (isVoice)
                        {
                            tune = tune + trackInt + "." + title + "【歌手】" + voice;
                        }
                        else if (isArtist)
                        {
                            tune = tune + trackInt + "." + title + "【歌手】" + artist;
                        }
                        else if (isOnlyComposer)
                        {
                            tune = tune + trackInt + "." + title + "【作曲】" + composer;
                        }
                        else
                        {
                            tune = tune + trackInt + "." + title + "【编曲】" + arrange;
                        }
                        if (isOrigin)
                        {
                            tune = tune + "【副标题】原曲:";
                            foreach (string og in origin)
                            {
                                tune = tune + og + " / ";
                            }
                            tune = tune.Remove(tune.Length - 3);
                        }

                        //字符修正,
                        tune = tune.Replace("&#39;", "'");
                        tune = tune.Replace("&#91;", "[");
                        tune = tune.Replace("&#93;", "]");
                        tune = tune.Replace(" ~", " ~");

                        albumInfoArray.Add(tune);
                        previousTrack = trackInt;
                    }
                }


                reader.Close();
                dataStream.Close();
                response.Close();

                string[] albumInfoString = new string[albumInfoArray.Count];
                for (int i = 0; i < albumInfoArray.Count; i++)
                {
                    albumInfoString[i] = (string)albumInfoArray[i];
                }
                File.WriteAllLines("专辑信息.txt", albumInfoString);
                File.WriteAllText("爬取.html", tuneInfo);

                Form2 form2 = new Form2(albumInfoArray);
                form2.Show();

                return(DateTime.Now + "  爬取成功");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                return(DateTime.Now + "  爬取失败");
            }
        }
Example #23
0
 private static string Username(Match m)
 {
     string x = m.ToString();
     string username = x.Replace("@", "");
     return x.Link("http://twitter.com/" + username);
 }
Example #24
0
 private string ToLowerCase(Match m)
 {
     return(m.ToString().ToLower());
 }
Example #25
0
        private static string HtmlDecode(string s, IDictionary <string, string> map)
        {
            Match m = RegExAnyEntity.Match(s);

            if (!m.Success)
            {
                return(s);
            }

            int           cpos = 0;
            StringBuilder b    = new StringBuilder(s.Length);

            while (m.Success)
            {
                b.Append(s.Substring(cpos, m.Index - cpos));
                string entity = m.ToString();
                string decoded;
                if (map.TryGetValue(entity, out decoded))
                {
                    b.Append(decoded);
                }
                else if (entity[1] == '#')
                {
                    // numeric entity
                    try
                    {
                        int etp;
                        int lCorr = 0;
                        if (entity[entity.Length - 1] == ';')
                        {
                            lCorr = 1;
                        }
                        if ((entity[2] == 'x') || (entity[2] == 'X'))
                        {
                            string ets = entity.Substring(3, entity.Length - 3 - lCorr);
                            etp = int.Parse(ets, NumberStyles.AllowHexSpecifier);
                        }
                        else
                        {
                            string ets = entity.Substring(2, entity.Length - 2 - lCorr);
                            etp = int.Parse(ets);
                        }
                        // in contrast to HttpUtility.HtmlDecode() we use the Encoding class and do not
                        // simply cast ushort to char and append...
                        Encoding encoding = (etp <= 0xff) ? Encoding.Default : Encoding.Unicode;
                        decoded = encoding.GetString(BitConverter.GetBytes(etp));
                        if (decoded.Length > 0)
                        {
                            decoded = decoded.Substring(0, 1);
                        }
                        b.Append(decoded);
                    }
                    catch (Exception ex)
                    {
                        // Format/Overflow from Int32.Parse()
                        _log.Error("HtmlDecode() match Exception for HTML entity '" + entity + "'", ex);
                        b.Append(entity); //
                    }
                }
                else
                {
                    //_log.Warn("HtmlDecode() unknown HTML entity: " + entity);
                    b.Append(entity); // just take over
                }

                // move current position and get next match
                cpos = m.Index + m.Length;
                m    = m.NextMatch();
            }

            // append all other missing chars after a match and return
            b.Append(s.Substring(cpos, s.Length - cpos));
            return(b.ToString());
        }
Example #26
0
    static void Main()
    {
        try
        {
            StreamReader  reader;
            StringBuilder content = new StringBuilder();
            string[]      words   = null;
            //read words from file
            using (reader = new StreamReader(@"../../words.txt", cyrillic))
            {
                while (!reader.EndOfStream)
                {
                    content.AppendLine(reader.ReadLine());
                }
                words = Regex.Split(content.ToString(), @"\s+");
            }
            //create pattern with words in file
            StringBuilder temp = new StringBuilder();
            foreach (string word in words)
            {
                if (word.Length > 0)
                {
                    temp.Append(word + "|");
                }
            }
            temp.Append("\b\0\b");
            string pattern = @"\b(" + temp + @")\b";

            Regex regex = new Regex(pattern);
            using (reader = new StreamReader(@"../../test.txt", cyrillic))
            {
                content.Clear();
                while (!reader.EndOfStream)
                {
                    content.Append(reader.ReadLine());
                }
            }
            Match match = regex.Match(content.ToString());

            Dictionary <string, int> pairs = new Dictionary <string, int>();
            while (match.Success)
            {
                string word = match.ToString();
                if (pairs.ContainsKey(word))
                {
                    pairs[word]++;
                }
                else
                {
                    pairs.Add(word, 1);
                }
                match = match.NextMatch();
            }

            using (StreamWriter output = new StreamWriter(@"../../result.txt", false, cyrillic))
            {
                foreach (var pair in pairs)
                {
                    output.WriteLine("word: {0} contained {1}", pair.Key, pair.Value);
                }
            }

            Console.WriteLine("Done.");
        }
        catch (IOException ioe)
        {
            Console.WriteLine(ioe.Message);
        }
    }
        private string GetLinkNameEvent(Match match)
        {
            //UUID eventID = new UUID(match.Groups["event_id"].Value);

            return(match.ToString());
        }
Example #28
0
        /// <summary>
        /// Matches the eval.
        /// </summary>
        /// <param name="match">The match.</param>
        /// <returns></returns>
        public string MatchEval(Match match)
        {
            if (match.Groups[1].Success) //comment
            {
                StringReader  reader = new StringReader(match.ToString());
                string        line;
                StringBuilder sb = new StringBuilder();
                while ((line = reader.ReadLine()) != null)
                {
                    Run r = new Run()
                    {
                        Text = line.ToString()
                    };
                    r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 57, 125, 2));

                    CodeParagraphGlobal.Add(r);
                }
                return("::::::");
            }
            else if (match.Groups[2].Success) //string literal
            {
                Run r = new Run()
                {
                    Text = match.ToString()
                };
                r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 0, 160, 0));

                CodeParagraphGlobal.Add(r);
                return("::::::");
            }
            else if (match.Groups[3].Success) //keyword
            {
                Run r = new Run()
                {
                    Text = match.ToString()
                };
                r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 0, 0, 255));

                CodeParagraphGlobal.Add(r);
                return("::::::");
            }
            else if (match.Groups[4].Success)//Numbers
            {
                Run r = new Run()
                {
                    Text = match.ToString()
                };
                r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 0, 0, 255));

                CodeParagraphGlobal.Add(r);
                return("::::::");
            }
            else if (match.Groups[5].Success)//Operators
            {
                Run r = new Run()
                {
                    Text = match.ToString()
                };
                r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 200, 200, 195));

                CodeParagraphGlobal.Add(r);
                return("::::::");
            }
            else if (match.Groups[6].Success)
            {
                Run r = new Run()
                {
                    Text = match.ToString()
                };
                r.Foreground = new SolidColorBrush(Color.FromArgb((byte)255, 0, 0, 0));

                CodeParagraphGlobal.Add(r);
                return("::::::");
            }
            else
            {
                return("");
            }
        }
        private string GetLinkNameTrackAvatar(Match match)
        {
            //UUID agentID = new UUID(match.Groups["friend_id"].Value);

            return(match.ToString());
        }
Example #30
0
        /// <summary>
        /// Takes a string and traverses it to create a ParseNode with associated values.
        /// </summary>
        /// <param name="s">The string to parse.</param>
        /// <param name="p">A partially-parsed node coming from multiline inputs in the REPL.</param>
        /// <returns>Returns the root ParseNode that represents the string.</returns>
        /// <exception cref="Exception">Thrown when the parser fails to parse an token.</exception>
        public override ParseNode Parse(string s, ParseNode p = null, bool keepComments = false)
        {
            var source = _rNewline.Split(s).ToList();
            var result = new ParseNode();
            var stack  = new List <ParseNode> {
                result
            };
            var current      = result;
            var depth        = 0;
            var commentDepth = 0;

            if (p != null)
            {
                result = p;
                stack  = new List <ParseNode> {
                    p
                };
                current      = result;
                depth        = 1;
                commentDepth = current.CommentDepth;
                while (true)
                {
                    if (current.Children.Count == 0)
                    {
                        break;
                    }
                    var last = current.Children.Last();
                    if (last.Children == null || last.Finished)
                    {
                        break;
                    }
                    current = last;
                    stack.Add(current);
                    depth++;
                    commentDepth = current.CommentDepth;
                }
            }
            foreach (var(line, row) in source.WithIndex())
            {
                var column = 0;
                while (column < line.Length)
                {
                    var       c        = line[column];
                    TokenType type     = TokenType.None;
                    Match     rawMatch = null;
                    string    value    = null;
                    string    match    = null;
                    if (current.UnfinishedString != null)
                    {
                        rawMatch = _rStringEnd.Match(line);
                        if (!rawMatch.Success)
                        {
                            current.UnfinishedString += Regex.Unescape(line);
                            column = line.Length;
                            continue;
                        }
                        match = rawMatch.ToString();
                        value = current.UnfinishedString + Regex.Unescape(match.Substring(0, match.Length - 1));
                        current.UnfinishedString = null;
                        type = TokenType.String;
                    }
                    else if (commentDepth > 0)
                    {
                        rawMatch = _rBlockCommentContinue.Match(line, column);
                        if (!rawMatch.Success)
                        {
                            current.UnfinishedComment += line;
                            column = line.Length;
                            continue;
                        }
                        match = rawMatch.ToString();
                        if (keepComments)
                        {
                            value = current.UnfinishedComment;
                            switch (match.Length)
                            {
                            case 2:
                                break;

                            case 3:
                                if (match[0] != ' ')
                                {
                                    value += match[0];
                                }
                                break;

                            default:
                                var start = match[0] == ' ' ? 1 : 0;
                                value += match.Substring(
                                    start, match.Length - (match[match.Length - 3] == ' ' ? 3 : 2) - start
                                    );
                                break;
                            }
                            type = TokenType.Comment;
                        }
                        if (rawMatch.Groups[1].Value == "#|")
                        {
                            commentDepth++;
                        }
                        else
                        {
                            commentDepth--;
                        }
                    }
                    else
                    {
                        switch (c)
                        {
                        // S-expressions
                        case '(':
                            depth++;
                            column++;
                            var next = new ParseNode();
                            current.Children.Add(next);
                            current = next;
                            stack.Add(current);
                            continue;

                        case ')':
                            if (--depth < 0)
                            {
                                throw new Exception("Unexpected ')' at top level");
                            }
                            column++;
                            current.Finish();
                            var finished = current;
                            stack.RemoveAt(stack.Count - 1);
                            current = stack.Last();
                            if (current.ExpectsList)
                            {
                                finished.IsList = true;
                            }
                            if (current.ExpectsDictionary)
                            {
                                finished.IsDictionary = true;
                            }
                            if (current.Children.Count > 1 && current.Children[current.Children.Count - 2].Token?.Type == TokenType.Cast)
                            {
                                var castNode = new ParseNode(new[] {
                                    new ParseNode(new Token(TokenType.Atom, current.Children[current.Children.Count - 2].Token.Literal)),
                                    finished
                                });
                                castNode.Finish();
                                current.Children[current.Children.Count - 2] = castNode;
                                current.Children.RemoveAt(current.Children.Count - 1);
                            }
                            continue;

                        // Variables
                        case '$':
                            match = _rScalar.Match(line, column).ToString();
                            if (match.Contains("|#"))
                            {
                                throw new Exception("Unexpected '|#' outside of comment");
                            }
                            if (match == "")
                            {
                                match = value = "$";
                                type  = TokenType.Cast;
                            }
                            else
                            {
                                value = match.Substring(1);
                                type  = TokenType.ScalarName;
                            }
                            break;

                        case '@':
                            match = _rList.Match(line, column).ToString();
                            if (match.Contains("|#"))
                            {
                                throw new Exception("Unexpected '|#' outside of comment");
                            }
                            if (match == "")
                            {
                                match = value = "@";
                                type  = TokenType.Cast;
                            }
                            else
                            {
                                value = match.Substring(1);
                                type  = TokenType.ListName;
                            }
                            break;

                        case '%':
                            match = _rDict.Match(line, column).ToString();
                            if (match.Contains("|#"))
                            {
                                throw new Exception("Unexpected '|#' outside of comment");
                            }
                            if (match == "")
                            {
                                match = value = "%";
                                type  = TokenType.Cast;
                            }
                            else
                            {
                                value = match.Substring(1);
                                type  = TokenType.DictionaryName;
                            }
                            break;

                        // Lists
                        case '\'':
                            current.ExpectsList = true;
                            column++;
                            continue;

                        // Dictionaries
                        case '`':
                            current.ExpectsDictionary = true;
                            column++;
                            continue;

                        // Strings
                        case '"':
                            rawMatch = _rString.Match(line, column);
                            if (!rawMatch.Success)
                            {
                                current.UnfinishedString = Regex.Unescape(_rStringStart.Match(line, column).ToString().Substring(1));
                                column = line.Length;
                                continue;
                            }
                            match = rawMatch.ToString();
                            value = Regex.Unescape(match.Substring(1, match.Length - 2));
                            type  = TokenType.String;
                            break;

                        // Numbers
                        case '-':
                        case char _ when char.IsDigit(c):
                            match = value = _rNumber.Match(line, column).ToString();

                            if (value == "-")
                            {
                                match = value = _rName.Match(line, column).ToString();
                                type  = TokenType.Atom;
                            }
                            else
                            {
                                type = value.Contains('.') ? TokenType.Float : TokenType.Integer;
                            }
                            break;

                        // Whitespace
                        case ' ':
                        case '\t':
                        case '\f':
                        case '\v':
                        case '\r':
                        case '\n':
                            match = _rWhitespace.Match(line, column).ToString();
                            break;

                        // Comments
                        case ';':
                            match = _rComment.Match(line, column).ToString();
                            if (keepComments)
                            {
                                value = match.Substring(match.Length > 2 && match[1] == ' ' ? 2 : 1);
                                type  = TokenType.Comment;
                            }
                            break;

                        case '#':
                            match = _rBlockCommentStart.Match(line, column).ToString();
                            if (match == null)
                            {
                                match = value = _rName.Match(line, column).ToString();
                                type  = TokenType.Atom;
                                break;
                            }
                            commentDepth++;
                            if (keepComments)
                            {
                                current.UnfinishedComment = "";
                                depth++;
                                column += match.Length;
                                next    = new ParseNode {
                                    IsComment = true
                                };
                                current.Children.Add(next);
                                current = next;
                                stack.Add(current);
                                continue;
                            }
                            break;

                        // Identifiers (default)
                        default:
                            match = value = _rName.Match(line, column).ToString();
                            if (match.Contains("|#"))
                            {
                                throw new Exception("Unexpected '|#' outside of comment");
                            }
                            type = TokenType.Atom;
                            break;
                        }
                    }
                    if (type != TokenType.None && (type != TokenType.Comment || value.Length != 0))
                    {
                        if (current.Children.Count != 0 && current.Children.Last().Token?.Type == TokenType.Cast)
                        {
                            current.Children[current.Children.Count - 1] = new ParseNode(new[] {
                                new ParseNode(new Token(TokenType.Atom, current.Children.Last().Token.Literal)),
                                new ParseNode(new Token(type, value))
                            });
                        }
                        else
                        {
                            current.Children.Add(new ParseNode(new Token(type, value)));
                        }
                    }
                    if (match.Length == 0)
                    {
                        throw new Exception($"Could not match token '{Regex.Escape("" + c)}' at {row + 1}:{column}");
                    }
                    column += match.Length;
                    if (type == TokenType.Comment)
                    {
                        if (match.Contains("#|"))
                        {
                            current.UnfinishedComment = "";
                            depth++;
                            var next = new ParseNode {
                                IsComment = true
                            };
                            current.Children.Add(next);
                            current = next;
                            stack.Add(current);
                            continue;
                        }
                        else
                        {
                            current.UnfinishedComment = "";
                            depth--;
                            current.Finish();
                            var finished = current;
                            stack.RemoveAt(stack.Count - 1);
                            current = stack.Last();
                        }
                    }
                }
            }
            if (commentDepth == 0 && current.UnfinishedString == null && (result.Children.Count() == 0 || result.Children.Last().Finished))
            {
                result.Finished = true;
            }
            else
            {
                current.CommentDepth = commentDepth;
            }
            return(result);
        }
        private string GetLinkNameWearFolder(Match match)
        {
            //UUID folderID = new UUID(match.Groups["inventory_folder_uuid"].Value);

            return(match.ToString());
        }
Example #32
0
        protected List <OSHttpHandler> MatchHandlers(OSHttpRequest req, List <OSHttpHandler> handlers)
        {
            Dictionary <OSHttpHandler, int> scoredHandlers = new Dictionary <OSHttpHandler, int>();

            _log.DebugFormat("[{0}] MatchHandlers for {1}", EngineID, req);

            foreach (OSHttpHandler h in handlers)
            {
                // initial anchor
                scoredHandlers[h] = 0;

                // first, check whether IPEndPointWhitelist applies
                // and, if it does, whether client is on that white
                // list.
                if (null != h.IPEndPointWhitelist)
                {
                    // TODO: following code requires code changes to
                    // HttpServer.HttpRequest to become functional
                    IPEndPoint remote = req.RemoteIPEndPoint;

                    if (null != remote)
                    {
                        Match epm = h.IPEndPointWhitelist.Match(remote.ToString());

                        if (!epm.Success)
                        {
                            scoredHandlers.Remove(h);
                            continue;
                        }
                    }
                }

                if (null != h.Method)
                {
                    Match m = h.Method.Match(req.HttpMethod);

                    if (!m.Success)
                    {
                        scoredHandlers.Remove(h);
                        continue;
                    }

                    scoredHandlers[h]++;
                }

                // whitelist ok, now check path
                if (null != h.Path)
                {
                    Match m = h.Path.Match(req.RawUrl);

                    if (!m.Success)
                    {
                        scoredHandlers.Remove(h);
                        continue;
                    }

                    scoredHandlers[h] += m.ToString().Length;
                }

                // whitelist & path ok, now check query string
                if (null != h.Query)
                {
                    int queriesMatch = MatchOnNameValueCollection(req.QueryString, h.Query);

                    if (0 == queriesMatch)
                    {
                        _log.DebugFormat("[{0}] request {1}", EngineID, req);
                        _log.DebugFormat("[{0}] dropping handler {1}", EngineID, h);

                        scoredHandlers.Remove(h);
                        continue;
                    }

                    scoredHandlers[h] += queriesMatch;
                }

                // whitelist, path, query string ok, now check headers
                if (null != h.Headers)
                {
                    int headersMatch = MatchOnNameValueCollection(req.Headers, h.Headers);

                    if (0 == headersMatch)
                    {
                        _log.DebugFormat("[{0}] request {1}", EngineID, req);
                        _log.DebugFormat("[{0}] dropping handler {1}", EngineID, h);

                        scoredHandlers.Remove(h);
                        continue;
                    }

                    scoredHandlers[h] += headersMatch;
                }
            }

            List <OSHttpHandler> matchingHandlers = new List <OSHttpHandler>(scoredHandlers.Keys);

            matchingHandlers.Sort(delegate(OSHttpHandler x, OSHttpHandler y)
            {
                return(scoredHandlers[x] - scoredHandlers[y]);
            });

            LogDumpHandlerList(matchingHandlers);
            return(matchingHandlers);
        }
Example #33
0
 public override string ToString()
 {
     return(Match.ToString().Trim().Replace('\n', ' ').Replace('\r', ' ').Replace("  ", " "));
 }
    private String SearchRegexpMatch(Regex r)
    {
        // マウスの位置をLineNoとColumnへと投影
        var pos    = Hm.Edit.MousePos;
        int lineno = pos.LineNo - 1;
        int column = pos.Column;

        // どちらかがはみ出ているならダメ
        if (lineno < 0 || column < 0)
        {
            HideForm();

            hepResultInfo.Reset();

            return("");
        }

        // テキスト全体を行単位に分解し
        String text = Hm.Edit.TotalText;

        char[] dlm = { '\n' };

        // 1行を文字単位で扱えるようにする。
        String[] split = text.Split(dlm, StringSplitOptions.None);


        // マウスの下にある単語の抽出
        String result = "";

        // 今の位置から1つずつ前へと調査し、
        // マッチしたもの全体が、現在のマウスの下のcolumnの位置を含んでいれば良い。
        // その条件に見合うもののうち、最も長大マッチするものが求める単語となる。
        int result_ix = 0;

        for (int ix = column; ix >= 0; ix--)
        {
            String target = split[lineno].Substring(ix);
            Match  m      = r.Match(target);
            if (m.Success)
            {
                // マッチしたものが、現在のcolumnの位置を含むのか。
                String current = m.ToString();
                if (column < ix + current.Length)
                {
                    result_ix = ix;
                    result    = m.ToString();
                }
            }
        }

        // 有効な単語が取得できたら
        if (result.Length > 0)
        {
            // このフォームを表示して
            ShowForm();

            hepResultInfo.Result = result;
            hepResultInfo.LineNo = pos.LineNo;
            hepResultInfo.Column = result_ix;
            hepResultInfo.LbText = result + "(lineno:" + pos.LineNo.ToString() + ", column:" + result_ix.ToString() + ")";

            // 現在ラベル内容を食い違うなら更新
            if ((String)lb.Text != hepResultInfo.LbText)
            {
                lb.Text = hepResultInfo.LbText;
                tsserver_ChangeTargetWord(pos.LineNo, hepResultInfo.Column + 1); // +1 するには、tsserverは、columnが1始まりだから。
            }

            return(result);
        }
        // 有効でないなら、フォーム自体を隠す
        else
        {
            HideForm();

            hepResultInfo.Reset();

            // Labelの中身も消滅
            if (lb.Text != "")
            {
                lb.Text       = "";
                lbDetail.Text = "";
            }

            return(result);
        }
    }
Example #35
0
        public void SearchSteam()
        {
            steamGameDirs.Clear();
            string      steam32 = "SOFTWARE\\VALVE\\";
            string      steam64 = "SOFTWARE\\Wow6432Node\\Valve\\";
            string      steam32path;
            string      steam64path;
            string      config32path;
            string      config64path;
            RegistryKey key32 = Registry.LocalMachine.OpenSubKey(steam32);
            RegistryKey key64 = Registry.LocalMachine.OpenSubKey(steam64);

            if (key64.ToString() == null || key64.ToString() == "")
            {
                foreach (string k32subKey in key32.GetSubKeyNames())
                {
                    using (RegistryKey subKey = key32.OpenSubKey(k32subKey))
                    {
                        steam32path  = subKey.GetValue("InstallPath").ToString();
                        config32path = steam32path + "/steamapps/libraryfolders.vdf";
                        string driveRegex = @"[A-Z]:\\";
                        if (File.Exists(config32path))
                        {
                            string[] configLines = File.ReadAllLines(config32path);
                            foreach (var item in configLines)
                            {
                                Match match = Regex.Match(item, driveRegex);
                                if (item != string.Empty && match.Success)
                                {
                                    string matched = match.ToString();
                                    string item2   = item.Substring(item.IndexOf(matched));
                                    item2 = item2.Replace("\\\\", "\\");
                                    item2 = item2.Replace("\"", "\\");
                                    if (Directory.Exists(item2 + "\\steamapps\\common"))
                                    {
                                        item2 = item2 + "steamapps\\common\\";
                                        steamGameDirs.Add(item2);
                                    }
                                }
                            }
                            steamGameDirs.Add(steam32path + "\\steamapps\\common\\");
                        }
                    }
                }
            }
            foreach (string k64subKey in key64.GetSubKeyNames())
            {
                using (RegistryKey subKey = key64.OpenSubKey(k64subKey))
                {
                    steam64path  = subKey.GetValue("InstallPath").ToString();
                    config64path = steam64path + "/steamapps/libraryfolders.vdf";
                    string driveRegex = @"[A-Z]:\\";
                    if (File.Exists(config64path))
                    {
                        string[] configLines = File.ReadAllLines(config64path);
                        foreach (var item in configLines)
                        {
                            Match match = Regex.Match(item, driveRegex);
                            if (item != string.Empty && match.Success)
                            {
                                string matched = match.ToString();
                                string item2   = item.Substring(item.IndexOf(matched));
                                item2 = item2.Replace("\\\\", "\\");
                                item2 = item2.Replace("\"", "\\");
                                if (Directory.Exists(item2 + "steamapps\\common"))
                                {
                                    item2 = item2 + "steamapps\\common\\";
                                    steamGameDirs.Add(item2);
                                }
                            }
                        }
                        steamGameDirs.Add(steam64path + "\\steamapps\\common\\");
                    }
                }
            }

            foreach (string item in steamGameDirs)
            {
                string   GameTitle;
                string   Exe1;
                string   Exe2;
                string   Exe3;
                string   Exe4;
                string   Exe5;
                string   Exe6;
                string[] Executables = new string[0];
                string[] steamGames  = Directory.GetDirectories(item);
                foreach (var dir in steamGames)
                {
                    GameTitle = null; Exe1 = null; Exe2 = null; Exe3 = null; Exe4 = null; Exe5 = null; Exe6 = null;
                    string   title  = dir.Substring(dir.IndexOf("\\common\\"));
                    string[] titlex = title.Split('\\');
                    title     = titlex[2].ToString();
                    GameTitle = title;
                    string[] executables = Directory.GetFiles(dir, "*.exe");
                    int      num         = 1;
                    foreach (var ex in executables)
                    {
                        if (num == 1)
                        {
                            Exe1 = ex;
                        }
                        if (num == 2)
                        {
                            Exe2 = ex;
                        }
                        if (num == 3)
                        {
                            Exe3 = ex;
                        }
                        if (num == 4)
                        {
                            Exe4 = ex;
                        }
                        if (num == 5)
                        {
                            Exe5 = ex;
                        }
                        if (num == 6)
                        {
                            Exe6 = ex;
                        }
                        num++;
                    }
                    if (GameTitle != "Steamworks Shared")
                    {
                        exes.Add(new GameExecutables
                        {
                            Title = GameTitle,
                            Exe1  = Exe1,
                            Exe2  = Exe2,
                            Exe3  = Exe3,
                            Exe4  = Exe4,
                            Exe5  = Exe5,
                            Exe6  = Exe6
                        });
                    }
                }
            }
        }
 public static String Rep1(Match input)
 {
     String s = String.Empty;
     if (String.Compare(input.ToString(), "Big", StringComparison.CurrentCultureIgnoreCase) == 0)
         s = "Huge";
     else
         s = "Tiny";
     return s;
 }
Example #37
0
        private static string DecodeCharacter(Match match)
        {
            string digits = match.ToString().TrimStart(new[] { '#', '&' }).TrimEnd(';').ToUpperInvariant();

            return(digits.StartsWith("X") ? HexToString(digits) : DecToString(digits));
        }
 public static String RepBold(Match m)
 {
     string str = m.ToString();
     return String.Format("<b>{0}</b>", str);
 }
Example #39
0
 private string ReplaceUrlWithHref(Match m)
 // Replace each Regex cc match with the number of the occurrence.
 {
     return("<a href='" + m.ToString() + "'>" + m.ToString() + "</a>");
 }
Example #40
0
    public static string MyMatchEvaluator(Match m)
    {
        matched = true;
        string matchedString = m.ToString();

        if (addJsType)
        {
            var lastDir = "";
            {
                // add "../../...." to reach Assets/
                int i = 0;
                var np = nextPath;
                while (true)
                {
                    i = np.IndexOf('/', i);
                    if (i < 0) break;
                    lastDir += "../";
                    i++;
                }
            }

            string JsTypeSection = string.Format("[JsType(JsMode.Clr,\"{0}{1}{2}{3}{4}\")]",
                lastDir, JSBindingSettings.sharpKitGenFileDir, nextPath, m.Groups["ClassName"], JSBindingSettings.jsExtension);

            // ���JsType�����Ѿ���������ͬ���Ͳ�Ҫ���ˣ�ֱ�ӷ�����ͬ�Ĵ�
            if (matchedString.IndexOf(JsTypeSection) >= 0)
                return matchedString;
            else
                return string.Format("\n{0}\n{1}", JsTypeSection, m.Groups["ClassDefinition"]);
        }
        else
        {
            // ���û�� JsType���Ͳ�Ҫ�滻�ˣ���Ϊ�滻��Ӹ�\n���ᵼ���ļ��޸�
            // ��Ȼ�������������� JsType���Ǿ��滻һ�£��Ӹ����У�Ҳû��
            if (matchedString.IndexOf("JsType") < 0)
                return matchedString;
            else
                return string.Format("\n{0}", m.Groups["ClassDefinition"]);
        }
    }
Example #41
0
 public override string ToString()
 {
     return("Match " + Match.ToString());
 }
Example #42
0
 private static string Hashtag(Match m)
 {
     string x = m.ToString();
     string tag = x.Replace("#", "%23");
     return x.Link("http://search.twitter.com/search?q=" + tag);
 }
 public static String Rep3(Match input)
 {
     String s = String.Empty;
     if (input.ToString().Equals("a"))
         s = "A";
     if (input.ToString().Equals("b"))
         s = "B";
     if (input.ToString().Equals("c"))
         s = "C";
     return s;
 }
Example #44
0
        /// <summary>
        /// Decodes a <see cref="Layer"/> into a <see cref="Texture2D"/>.
        /// </summary>
        /// <param name="layer">The <see cref="Layer"/> to decode.</param>
        /// <returns>The <see cref="Texture2D"/> decoded from the layer.</returns>
        public static Texture2D DecodeImage(Layer layer)
        {
            if (layer.Rect.width == 0 || layer.Rect.height == 0)
            {
                return(null);
            }

            Texture2D texture = new Texture2D((int)layer.Rect.width, (int)layer.Rect.height, TextureFormat.ARGB32, false);

            Color32[] colors = new Color32[(int)(layer.Rect.width * layer.Rect.height)];

            for (int y = 0; y < layer.Rect.height; ++y)
            {
                int layerRow = y * (int)layer.Rect.width;

                // we need to reverse the Y position for the Unity texture
                int textureRow = ((int)layer.Rect.height - 1 - y) * (int)layer.Rect.width;

                for (int x = 0; x < layer.Rect.width; ++x)
                {
                    int layerPosition   = layerRow + x;
                    int texturePosition = textureRow + x;

                    colors[texturePosition] = GetColor(layer, layerPosition);

                    //// set the alpha
                    //if(layer.SortedChannels.ContainsKey(-2))
                    //{
                    //    byte color = GetColor(layer.MaskData, x, y);
                    //    colors[texturePosition].a = (byte)(colors[texturePosition].a * color);
                    //}
                }
            }

            texture.SetPixels32(colors);

            if (layer.Is9Slice)
            {
                Regex    reg   = Layer.SLICE_REG;
                Match    match = reg.Match(layer.Name);
                string[] size  = match.Success ? match.ToString().Split(Layer.SLICE_SEPECTOR) : new string[] { "5", "5" };

                int width  = 0;
                int height = 0;
                //l t r b     Border l b r t
                // y w
                if (layer.Border.x == 0 || layer.Border.z == 0)
                {
                    width  = (int)layer.Rect.width;
                    height = int.Parse(size[1]);
                }
                else if (layer.Border.y == 0 || layer.Border.w == 0)
                {
                    height = (int)layer.Rect.height;
                    width  = int.Parse(size[0]);
                }

                if (layer.Border.x != 0 && layer.Border.y != 0 && layer.Border.z != 0 && layer.Border.w != 0 && size.Length >= 2)
                {
                    width  = int.Parse(size[0]);
                    height = int.Parse(size[1]);
                }

                int destWidth  = (int)(layer.Border.x + layer.Border.z + width);
                int destHeight = (int)(layer.Border.y + layer.Border.w + height);

                float scaleFactorX = (texture.width * 1.0f - layer.Border.x - layer.Border.z) / width;
                float scaleFactorY = (texture.height * 1.0f - layer.Border.y - layer.Border.w) / height;

                return(Util9Slice.Create9Slice(texture, new Params((int)layer.Border.x, (int)layer.Border.z, (int)layer.Border.w, (int)layer.Border.y,
                                                                   width, height, destWidth, destHeight, scaleFactorX, scaleFactorY)));
            }

            return(texture);
        }
Example #45
0
 /// <summary>
 /// Evaluates whether the text has spaces, page breaks, etc. and removes them.
 /// </summary>
 /// <param name="Matcher">The matched text</param>
 /// <returns>Stripped text</returns>
 private static string Evaluate(Match Matcher)
 {
     string MyString = Matcher.ToString();
     if (string.IsNullOrEmpty(MyString))
         return "";
     MyString = Regex.Replace(MyString, @"\r\n\s*", "");
     return MyString;
 }
Example #46
0
 public override string ToString() => Success?Match.ToString() : "No matches!";
Example #47
0
    public static string MyMatchEvaluator(Match m)
    {
        matched = true;
        string matchedString = m.ToString();

        if (addJsType)
        {
            var lastDir = "";
            {
                // add "../../...." to reach Assets/
                int i = 0;
                var np = nextPath;
                while (true)
                {
                    i = np.IndexOf('/', i);
                    if (i < 0) break;
                    lastDir += "../";
                    i++;
                }
            }

            string JsTypeSection = string.Format("[JsType(JsMode.Clr,\"{0}{1}{2}{3}{4}\")]", 
                lastDir, JSBindingSettings.sharpKitGenFileDir, nextPath, m.Groups["ClassName"], JSBindingSettings.jsExtension);

            // 如果JsType定义已经存在且相同,就不要改了,直接返回相同的串
            if (matchedString.IndexOf(JsTypeSection) >= 0)
                return matchedString;
            else
                return string.Format("\n{0}\n{1}", JsTypeSection, m.Groups["ClassDefinition"]);
        }
        else
        {
            // 如果没有 JsType,就不要替换了,因为替换会加个\n,会导致文件修改
            // 当然如果你的类名包含 JsType,那就替换一下,加个换行,也没事
            if (matchedString.IndexOf("JsType") < 0)
                return matchedString;
            else
                return string.Format("\n{0}", m.Groups["ClassDefinition"]);
        }
    }
Example #48
0
        static private QueryPart MatchToQueryPart(Match m)
        {
            // Looping over all Matches we have got:
            // m.Groups["pm"]	plus or minus sign
            // m.Groups["key"]	keyname
            // m.Groups["quote"]	quoted string
            // m.Groups["midquote1"] + m.Groups["midquote2"] quoted midway string also represents unquoted string

            string query = m.ToString();
            // Either quote is set or midquote1 and (optionally) midquote2 is set
            string text = m.Groups ["quote"].ToString() + m.Groups ["midquote1"].ToString() + m.Groups ["midquote2"].ToString();
            string key  = m.Groups ["key"].ToString();

            bool IsProhibited = (m.Groups ["pm"].ToString() == "-");


            // check for file extensions
            // if match starts with *. or . and only contains letters we assume it's a file extension
            if (extension_re.Match(text).Success || key.ToLower() == "ext" || key.ToLower() == "extension")
            {
                QueryPart_Property query_part = new QueryPart_Property();

                query_part.Key = Property.FilenameExtensionPropKey;

                if (text.StartsWith("*."))
                {
                    query_part.Value = text.Substring(1).ToLower();
                }
                else if (text.StartsWith("."))
                {
                    query_part.Value = text.ToLower();
                }
                else
                {
                    query_part.Value = "." + text.ToLower();
                }

                query_part.Type  = PropertyType.Keyword;
                query_part.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);

                Logger.Log.Debug("Extension query: {0}", query_part.Value);

                return(query_part);
            }

            if (key == String.Empty)
            {
                Logger.Log.Debug("Parsed query '{0}' as text_query", text);

                return(StringToQueryPart(text, IsProhibited));
            }

            // FIXME: i18n-izing "date"
            if (key == "date")
            {
                try {
                    QueryPart part = DateQueryToQueryPart(text);
                    part.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);
                    return(part);
                } catch (FormatException) {
                    Log.Warn("Could not parse [{0}] as date query. Assuming text.", text);
                    return(StringToQueryPart(text, IsProhibited));
                }
            }

            // FIXME: i18n-izing "uri"
            if (key == "uri")
            {
                try {
                    QueryPart_Uri part = new QueryPart_Uri();
                    part.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);
                    // uri: queries require the raw Uri as present in the index
                    part.Uri = new Uri(text, true);
                    return(part);
                } catch (System.UriFormatException) {
                    Log.Warn("Could not parse [{0}] as uri query. Assuming text.", text);
                    return(StringToQueryPart(text, IsProhibited));
                }
            }

            // Special case
            if (key == "inuri")
            {
                QueryPart_Property inuri_part = new QueryPart_Property();
                inuri_part.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);
                inuri_part.Key   = "inuri";
                inuri_part.Value = text;
                inuri_part.Type  = PropertyType.Keyword;
                Log.Debug("Handing special query 'inuri:{0}'", text);
                return(inuri_part);
            }

            // Non-keyword queries by directly using property names
            // Query of form property:namespace:name=value
            // which is translated to a non-keyword query
            // namespace:name=value
            int pos;

            if (key == "property" && ((pos = text.IndexOf('=')) != -1))
            {
                QueryPart_Property part = new QueryPart_Property();
                part.Key   = text.Substring(0, pos);
                part.Value = text.Substring(pos + 1);
                part.Type  = PropertyType.Text;
                part.Logic = (IsProhibited ?      QueryPartLogic.Prohibited : QueryPartLogic.Required);
                Logger.Log.Debug("Parsed query '" + query +
                                 "' as prop query:key=" + part.Key +
                                 ", value=" + part.Value +
                                 " and property type=" + part.Type);

                return(part);
            }

            // keyword queries by directly using property names
            // Query of form keyword:namespace:name=value
            // which is translated to a keyword query
            // namespace:name=value
            if (key == "keyword" && ((pos = text.IndexOf('=')) != -1))
            {
                QueryPart_Property part = new QueryPart_Property();
                part.Key   = text.Substring(0, pos);
                part.Value = text.Substring(pos + 1);
                part.Type  = PropertyType.Keyword;
                part.Logic = (IsProhibited ?      QueryPartLogic.Prohibited : QueryPartLogic.Required);
                Logger.Log.Debug("Parsed query '" + query +
                                 "' as prop query:key=" + part.Key +
                                 ", value=" + part.Value +
                                 " and property type=" + part.Type);

                return(part);
            }

            string[] prop_string = null;
            bool     is_present;

            PropertyType[] prop_type;
            int            num;

            is_present = PropertyKeywordFu.GetMapping(key, out num, out prop_string, out prop_type);
            // if key is not present in the mapping, assume the query is a text query
            // i.e. if token is foo:bar and there is no mappable property named foo,
            // assume "foo:bar" as text query
            // FIXME the analyzer changes the text query "foo:bar" to "foo bar"
            // which might not be the right thing to do

            if (!is_present)
            {
                Logger.Log.Warn("Could not find property, parsed query '{0}' as text_query", query);

                return(StringToQueryPart(query, IsProhibited));
            }

            if (num == 1)
            {
                QueryPart_Property query_part_prop = new QueryPart_Property();
                query_part_prop.Key   = prop_string [0];
                query_part_prop.Value = text;
                query_part_prop.Type  = prop_type [0];
                query_part_prop.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);

                Logger.Log.Debug("Parsed query '" + query +
                                 "' as prop query:key=" + query_part_prop.Key +
                                 ", value=" + query_part_prop.Value +
                                 " and property type=" + query_part_prop.Type);

                return(query_part_prop);
            }

            // Multiple property queries are mapped to this keyword query
            // Create an OR query from them
            // FIXME: Would anyone want an AND query ?

            QueryPart_Or query_part_or = new QueryPart_Or();

            query_part_or.Logic = (IsProhibited ? QueryPartLogic.Prohibited : QueryPartLogic.Required);

            Logger.Log.Debug("Parsed query '{0}' as OR of {1} queries:", query, num);

            for (int i = 0; i < num; ++i)
            {
                QueryPart_Property query_part_prop = new QueryPart_Property();
                query_part_prop.Key   = prop_string [i];
                query_part_prop.Value = text;
                query_part_prop.Type  = prop_type [i];
                query_part_prop.Logic = QueryPartLogic.Required;

                Log.Debug("\t:key={0}, value={1} and property type={2}", query_part_prop.Key, query_part_prop.Value, query_part_prop.Type);
                query_part_or.Add(query_part_prop);
            }

            return(query_part_or);
        }