Example #1
0
            /// <summary>
            /// 转换文字里的字符集
            /// </summary>
            /// <param name="p_Text"></param>
            /// <returns></returns>
            public string GetReadText(string p_Text)
            {
                System.Text.RegularExpressions.Regex           _Regex      = new System.Text.RegularExpressions.Regex(@"(?<=\=\?).*?(\?\=)+");
                System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(p_Text);
                string _Text = p_Text;

                foreach (System.Text.RegularExpressions.Match _Match in _Collection)
                {
                    string _Value = "=?" + _Match.Value;
                    if (_Value[0] == '=')
                    {
                        string[] _BaseData = _Value.Split('?');
                        if (_BaseData.Length == 5)
                        {
                            System.Text.Encoding _Coding = System.Text.Encoding.GetEncoding(_BaseData[1]);
                            if (_BaseData[2] == "B")
                            {
                                _Text = _Text.Replace(_Value, DecodeBase64(_BaseData[3], _Coding));
                            }
                            else
                            {
                                _Text = _Text.Replace(_Value, DecodeQuotedPrintable(_BaseData[3], _Coding));
                            }
                        }
                    }
                    else
                    {
                    }
                }
                return(_Text);
            }
Example #2
0
        public ResultModel <object> SetRound()
        {  //签名信息
            string fileContent = ETS.IO.FileIO.GetFileContent(System.AppDomain.CurrentDomain.BaseDirectory + "/Content/OpenRange.txt", Encoding.Default).Replace("\r", "").Replace("\n", "");

            System.Text.RegularExpressions.MatchCollection matchs = System.Text.RegularExpressions.Regex.Matches(fileContent, "!(.*?)--");
            int tmp = 0;

            foreach (System.Text.RegularExpressions.Match item in matchs)
            {
                tmp++;
                string        zuobiao = item.Groups[1].Value;
                List <string> @params = new List <string>()
                {
                    "timestamp=" + TimeHelper.GetTimeStamp(false),
                    "app_area_code=" + tmp,
                    "min_price=10",
                    "area=[" + zuobiao + "]",
                    "app_id=33"
                };
                @params.Sort();
                string url    = "http://waimaiopen.meituan.com/api/v1/third_shipping/save?";
                string waimd5 = url + string.Join("&", @params) + "96DD2B96BB9A7C49DC545DD17463CDFA"; //consumer_secret
                string sig    = ETS.Security.MD5.Encrypt(waimd5).ToLower();
                string paras  = string.Join("&", @params) + "&sig=" + sig;
                string json   = HTTPHelper.HttpPost(url, paras, accept: "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            }

            return(null);
        }
Example #3
0
        void Details_FormatPhoneNo(ref TextBox TextBox)
        {
            System.Text.RegularExpressions.MatchCollection Matches = System.Text.RegularExpressions.Regex.Matches(TextBox.Text, "[0-9]");
            TextBox.Text = "";
            System.Text.StringBuilder Sb = new System.Text.StringBuilder();
            foreach (System.Text.RegularExpressions.Match Match in Matches)
            {
                Sb.Append(Match.Value);
            }
            string Formatted = "";

            Formatted = Sb.ToString();

            Sb.Clear();
            try
            { Sb.Append("(" + Do_Methods.TextFiller(Strings.Mid(Formatted, 1, 3), "0", 3) + ")"); }
            catch { }
            try
            { Sb.Append("-" + Do_Methods.TextFiller(Strings.Mid(Formatted, 4, 3), "0", 3) + ""); }
            catch { }
            try
            { Sb.Append("-" + Do_Methods.TextFiller(Strings.Mid(Formatted, 7, 4), "0", 3) + ""); }
            catch { }

            TextBox.Text = Sb.ToString();
        }
Example #4
0
 public static IEnumerable <System.Text.RegularExpressions.Match> AsEnumeable(this System.Text.RegularExpressions.MatchCollection mc)
 {
     foreach (System.Text.RegularExpressions.Match m in mc)
     {
         yield return(m);
     }
 }
        private void _getBing_Click(object sender, RoutedEventArgs e)
        {
            string xmlDoc = string.Empty;

            try
            {
                HttpWebRequest oHttp_Web_Req = (HttpWebRequest)WebRequest.Create("https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1");
                Stream         oStream       = oHttp_Web_Req.GetResponse().GetResponseStream();
                using (StreamReader respStreamReader = new StreamReader(oStream, Encoding.UTF8))
                {
                    string line = string.Empty;
                    while ((line = respStreamReader.ReadLine()) != null)
                    {
                        xmlDoc += line;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            System.Text.RegularExpressions.Regex           regex      = new System.Text.RegularExpressions.Regex("<Url>(?<MyUrl>.*?)</Url>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.MatchCollection collection = regex.Matches(xmlDoc);
            // 取得匹配项列表
            string ImageUrl = "http://www.bing.com" + collection[0].Groups["MyUrl"].Value;

            if (true)
            {
                ImageUrl = ImageUrl.Replace("1366x768", "1920x1080");
            }

            downloadImg(ImageUrl);
        }
        /// <summary>
        /// Parse special color-changing instructions inside the text.
        /// </summary>
        private void ParseColorInstructions()
        {
            // clear previous color instructions
            _colorInstructions.Clear();

            // if color instructions are disabled, stop here
            if (!EnableColorInstructions)
            {
                return;
            }

            // find and parse color instructions
            if (_text.Contains("{{"))
            {
                int iLastLength = 0;
                System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex("{{[^{}]*}}");

                System.Text.RegularExpressions.MatchCollection oMatches = oRegex.Matches(_text);
                foreach (System.Text.RegularExpressions.Match oMatch in oMatches)
                {
                    string sColor = oMatch.Value.Substring(2, oMatch.Value.Length - 4);

                    _colorInstructions.Add(oMatch.Index - iLastLength, new ColorInstruction(sColor));
                    iLastLength += oMatch.Value.Length;
                }

                // Strip out the color instructions from the text to allow the rest of processing to process the actual text content
                _text = oRegex.Replace(_text, string.Empty);
            }
        }
Example #7
0
 private static bool Step002_CheckChars(string sql, ref string Msg)
 {
     if (sql.IndexOf("--") > -1)
     {
         Msg = "注释符号导致检测不通过";
         return(false);
     }
     if (sql.IndexOf(";") > -1)
     {
         Msg = "分号导致检测不通过";
         return(false);
     }
     if (System.Text.RegularExpressions.Regex.IsMatch(sql, @"(\r\n|\n)"))
     {
         Msg = "换行符导致检测不通过";
         return(false);
     }
     System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(sql, @"'");
     if (mc.Count > 0)
     {
         if (mc.Count % 2 != 0)
         {
             Msg = "单引号导致检测不通过";
             return(false);
         }
     }
     return(true);
 }
        public int DetectPhoneNumber(String value, ref String values)
        {
            String[] patterns =
            {
                @"(^|\W)01[01]\d{7,8}(\W|$)",                                                         //전화번호
                @"(^|\W)01[01]-\d{3,4}-\d{4}(\W|$)",                                                  //전화번호
                @"[0-9]{6}-[0-9]{7}",                                                                 //주민등록번호
                @"[0-9] [0-9] [01] [0-9] [0123] [0-9]-[1234] [0-9]{6}",                               //주민등록번호
                @"^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$", //이메일
                Search.Text                                                                           //검색글자
            };
            int count = 0;

            foreach (String pattern in patterns)
            {
                System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(value, pattern);

                foreach (System.Text.RegularExpressions.Match m in matches)
                {
                    if (m.Value != "")
                    {
                        ++count;
                        values += m + "\n";
                    }
                }
            }
            return(count);
        }
Example #9
0
            private void SetConfig(string p)
            {
                try
                {
                    System.Threading.Thread.Sleep(10);
                    System.Text.RegularExpressions.MatchCollection matches = confRegEX.Matches(p);
                    int key = int.Parse(matches[0].Groups[1].Value);

                    if (configTable.Keys.Contains(key))
                    {
                        if (configTable[key] is int)
                        {
                            configTable[key] = int.Parse(matches[0].Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (configTable[key] is decimal)
                        {
                            configTable[key] = decimal.Parse(matches[0].Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (configTable[key] is bool)
                        {
                            configTable[key] = int.Parse(matches[0].Groups[2].Value) == 0 ? false : true;
                        }

                        EnqueueTX("ok");
                    }
                    else
                    {
                        EnqueueTX("error");
                    }
                }
                catch (Exception ex)
                {
                    EnqueueTX("error");
                }
            }
        public string SearchDescriptions(string Name)
        {
            string HtmlFile = null;

            try
            {
                System.Net.WebClient WC = new System.Net.WebClient();
                WC.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
                WC.Encoding = System.Text.Encoding.UTF8;
                string Str = WC.DownloadString("http://www.kinomania.ru/search/?q=" + System.IO.Path.GetFileName(Name));

                System.Text.RegularExpressions.Regex Regul = new System.Text.RegularExpressions.Regex("<header><h3>По вашему запросу ничего не найдено</h3></header>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                bool Bool = Regul.IsMatch(Str);


                if (Bool == true)
                {
                    HtmlFile = "<html><div>Описание не найдено.</div><div>Попробуйте переименовать торрент файл</div></html>";
                }
                else
                {
                    Regul = new System.Text.RegularExpressions.Regex("(?<=fid=\").*(?=\">)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    System.Text.RegularExpressions.MatchCollection HTML = Regul.Matches(Str);
                    string FidStr = HTML[0].Value;



                    Str = WC.DownloadString("http://www.kinomania.ru/film/" + FidStr);

                    Regul = new System.Text.RegularExpressions.Regex("(?<=<title>).*(?=</title>)");
                    HTML  = Regul.Matches(Str);
                    string TitleStr = "<div>" + HTML[0].Value.Replace("| KINOMANIA.RU", "") + "</div>";

                    Regul = new System.Text.RegularExpressions.Regex("(<img width=\"295\")(\\n|.)*?(/>)");
                    HTML  = Regul.Matches(Str);
                    string OblojkaStr = HTML[0].Value.Replace("width=\"295\" height=\"434\"", "width=\"200\" height=\"320\"");

                    Regul = new System.Text.RegularExpressions.Regex("(<div class=\"l-col l-col-2\">)(\\n|.)*?(</div>)");
                    HTML  = Regul.Matches(Str);
                    string ObzorStr = HTML[0].Value.Replace("<div class=\"l-col l-col-2\">", "<div class=\"l-col l-col-2\"><font size=\"1\">");

                    Regul = new System.Text.RegularExpressions.Regex("(<div class=\"l-col l-col-3\">)(\\n|.)*?(<section)");
                    HTML  = Regul.Matches(Str);
                    string SozdateliStr = HTML[0].Value.Replace("<div class=\"l-col l-col-3\">", "<div class=\"l-col l-col-3\"><font size=\"1\">");

                    Regul = new System.Text.RegularExpressions.Regex("(<h2 class=\"b-switcher\">)(\\n|.)*?(</div>)");
                    HTML  = Regul.Matches(Str);
                    string OFilmeStr = "<div " + System.Environment.NewLine + HTML[0].Value.Replace("<h2 class=\"b-switcher\">", "<h2 class=\"b-switcher\"><font size=\"2\">") + "</div></div></div>";



                    HtmlFile = "<html>" + TitleStr + "<table><tbody><tr><td valign=\"top\">" + OblojkaStr + "</td><td valign=\"top\">" + ObzorStr + " <div></td><td valign=\"top\">" + SozdateliStr + "</div>" + "</td></tr></tbody></table>" + OFilmeStr + "</html>";
                }
            }
            catch (Exception ex)
            {
                HtmlFile = ex.Message;
            }
            return(HtmlFile);
        }
Example #11
0
        } // End Sub ReplaceGithubUser

        static void DisplayRegexResult(string input, string pattern)
        {
            System.Text.RegularExpressions.MatchCollection matches =
                System.Text.RegularExpressions.Regex.Matches(input, pattern);

            if (matches.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match thisMatch in matches)
                {
                    foreach (System.Text.RegularExpressions.Group thisGroup in thisMatch.Groups)
                    {
                        System.Console.WriteLine($"thisGroup: {thisGroup.Value}");

                        foreach (System.Text.RegularExpressions.Capture capture in thisGroup.Captures)
                        {
                            System.Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
                        } // Next capture
                    }     // Next thisGroup

                    foreach (System.Text.RegularExpressions.Capture capture in thisMatch.Captures)
                    {
                        System.Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
                    } // Next capture
                }     // Next thisMatch
            }         // End if (matches.Count > 0)
        }             // End Sub DisplayRegexResult
        public List <Uri> ExtractURLs(string str, Uri parentUrl)
        {
            string RegexPattern = @"<a.*?href=[""'](?<url>.*?)[""'].*?>(?<name>.*?)</a>";

            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(
                str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            var result = new List <Uri>();

            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var url = match.Groups["url"].Value;
                try
                {
                    var uri = new Uri(url);
                    if (url.Contains("http://") && uri.Host != parentUrl.Host)
                    {
                        result.Add(uri);
                    }
                }
                catch (UriFormatException)
                {
                }
            }

            return(result);
        }
Example #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bulk">string containing emails or kerb ids</param>
        /// <param name="isEmail">is the bulk vale an list of emails or kerb ids?</param>
        /// <param name="id">Workgroup Id</param>
        /// <param name="role">Role being for people being added</param>
        /// <param name="workgroup">workgroup</param>
        /// <param name="successCount">how many have already been successfully added</param>
        /// <param name="lookupUser">user being added</param>
        /// <param name="failCount">count of number not added</param>
        /// <param name="duplicateCount"> </param>
        /// <param name="notAddedKvp">list of users not added and reason why.</param>
        /// <returns></returns>
        public int TryBulkLoadPeople(string bulk, bool isEmail, int id, Role role, Workgroup workgroup, int successCount, ref int failCount, ref int duplicateCount, List <KeyValuePair <string, string> > notAddedKvp)
        {
            const string regexEmailPattern = @"\b[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}\b";
            const string regexKerbPattern  = @"\b[A-Z0-9]{2,10}\b";
            string       pattern;

            if (isEmail)
            {
                pattern = regexEmailPattern;
            }
            else
            {
                pattern = regexKerbPattern;
            }

            // Find matches
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(bulk, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var temp = match.ToString().ToLower();
                successCount = TryToAddPeople(id, role, workgroup, successCount, temp, ref failCount, ref duplicateCount, notAddedKvp);
            }

            return(successCount);
        }
        public static List <string> ExtractEmails(string str)

        {
            string RegexPattern = @"\b[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}\b";

            // Find matches

            System.Text.RegularExpressions.MatchCollection matches

                = System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            List <string> MatchList = new List <string>(matches.Count);

            // add each match

            int c = 0;

            foreach (System.Text.RegularExpressions.Match match in matches)

            {
                MatchList.Add(match.ToString());

                c++;
            }

            return(MatchList);
        }
Example #15
0
 public static System.Collections.Specialized.NameValueCollection Decode(string markString)
 {
     System.Text.RegularExpressions.MatchCollection _matckresult = _decodeReg.Matches(markString);
     if (_matckresult.Count > 0)
     {
         System.Collections.Specialized.NameValueCollection marks = new System.Collections.Specialized.NameValueCollection();
         for (int i = 0; i < _matckresult.Count; i++)
         {
             System.Text.RegularExpressions.Match match = _matckresult[i];
             string tempname, tempvalue;
             if (match.Value.IndexOf('=') > 0)
             {
                 tempname  = match.Value.Substring(0, match.Value.IndexOf('='));
                 tempvalue = match.Value.Substring(match.Value.IndexOf('=') + 1);
             }
             else
             {
                 tempname  = match.Value;
                 tempvalue = string.Empty;
             }
             tempname = tempname.Trim();
             if (!string.IsNullOrEmpty(tempvalue))
             {
                 tempvalue = tempvalue.Trim(' ', tempvalue[0]);
             }
             marks.Add(tempname, tempvalue);
         }
         return(marks);
     }
     else
     {
         throw new Exception(string.Format("Can not analyze \"{0}\"", markString));
     }
 }
        private void ParseColorInstructions()
        {
            p_ColorInstructions.Clear();

            if (!EnableColorInstructions)
            {
                return;
            }

            if (p_Text.Contains("{{"))
            {
                int iLastLength = 0;
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("{{[^{}]*}}");

                System.Text.RegularExpressions.MatchCollection matchCollection = regex.Matches(p_Text);
                foreach (System.Text.RegularExpressions.Match m in matchCollection)
                {
                    string sColor = m.Value.Substring(2, m.Value.Length - 4);

                    p_ColorInstructions.Add(m.Index - iLastLength, new ColorInstruction(sColor));
                    iLastLength += m.Value.Length;
                }

                p_Text = regex.Replace(p_Text, string.Empty);
            }
        }
Example #17
0
        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            int    chars      = 140;
            string tempstring = textBox1.Text;

            chars -= System.Text.RegularExpressions.Regex.Matches(tempstring, "http").Count * 20;
            chars -= System.Text.RegularExpressions.Regex.Matches(tempstring, "www").Count * 20;

            System.Text.RegularExpressions.Regex urlRx = new System.Text.RegularExpressions.Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            System.Text.RegularExpressions.MatchCollection matches = urlRx.Matches(tempstring);

            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var url = match.Groups["url"].Value;
                tempstring = tempstring.Replace(url, "");
            }
            chars         -= tempstring.Length;
            CharactersLeft = chars;

            charleft.Text = CharactersLeft.ToString();
            if (CharactersLeft < 0)
            {
                charleft.Foreground = new SolidColorBrush(Colors.Red);
            }
            else if (CharactersLeft > 140)
            {
                TweetButton.Content = "Cancel";
            }
            else
            {
                charleft.Foreground = new SolidColorBrush(Colors.Black);
                TweetButton.Content = "Send";
            }
        }
Example #18
0
        public override string PostProcessData(string DATATABLE)
        {
            if (this is HasIntervals)
            {
                System.Text.RegularExpressions.Regex intervalRx = new System.Text.RegularExpressions.Regex(@"{id:\s'(i|interval).+?'"
                                                                                                           , System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                System.Text.RegularExpressions.MatchCollection mc = intervalRx.Matches(DATATABLE);

                int i = 0;
                foreach (System.Text.RegularExpressions.Match mm in mc)
                {
                    if (mm.Success)
                    {
                        DATATABLE = DATATABLE.Replace(mm.Value, string.Format("{{id: 'i{0}', role: 'interval'", i));
                    }
                    i++;
                }
                // for intervalues we need to hack the JSON code to include role:'interval' after the naming
                return(DATATABLE);
            }
            else
            {
                return(DATATABLE);
            }
        }
Example #19
0
        /// <summary>Speak the text.</summary>
        public void Speak()
        {
            Silence();
            stack.Clear();
            clipDict.Clear();

            foreach (AudioClip clip in Clips)
            {
                clipDict.Add("#" + clip.name + "#", clip);
            }

            string[] speechParts = splitRegex.Split(Text).Where(s => s != string.Empty).ToArray();

            System.Text.RegularExpressions.MatchCollection mc = splitRegex.Matches(Text);

            int index = 0;

            foreach (System.Text.RegularExpressions.Match match in mc)
            {
                //Debug.Log("MATCH: '" + match + "' - " + Text.IndexOf(match.ToString(), index));
                stack.Add(index = Text.IndexOf(match.ToString(), index), match.ToString());
                index++;
            }

            index = 0;
            foreach (string speech in speechParts)
            {
                //Debug.Log("PART: '" + speech + "' - " + Text.IndexOf(speech, index));
                stack.Add(index = Text.IndexOf(speech, index), speech);
                index++;
            }

            StartCoroutine(processStack());
        }
Example #20
0
        public bool SetValueIfKeyExist(string p)
        {
            try
            {
                if (IsSetConf(p))
                {
                    System.Text.RegularExpressions.MatchCollection matches = ConfRegEX.Matches(p);
                    int     key = int.Parse(matches[0].Groups[1].Value);
                    decimal val = decimal.Parse(matches[0].Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture);

                    if (!ContainsKey(key))
                    {
                        return(false);
                    }

                    SetValue(key, val);
                    return(true);
                }
            }
            catch (Exception)
            {
            }

            return(false);
        }
Example #21
0
        /// <summary>
        /// Remove emoticons (emoji) from string
        /// </summary>
        /// <param name="input">Input/string complete to be removed the emoticons</param>
        /// <returns>Just string without emoticons</returns>
        public static string RemoveEmoticons(this string input)
        {
            string ret = string.Empty;

            /* ########################################################################
             #                                                                        #
             #  Obs: Description of each "group" Regex to be removed                  #
             #                                                                        #
             #   "[\x1F600-\x1F64F]" ==> Emoticons                                    #
             #   "[\x1F300-\x1F5FF]" ==> Miscellaneous Symbols and Pictographs        #
             #   "[\x1F680-\x1F6FF]" ==> Match Transport And Map Symbols              #
             #   "[\x1F1E0-\x1F1FF]" ==> Match flags (iOS)                            #
             #                                                                        #
             ######################################################################### */

            string regexEmoticons = "[\x1F600-\x1F64F\x1F300-\x1F5FF\x1F680-\x1F6FF\x1F1E0-\x1F1FF?!( !@#$%¨&*\"'!;.:,?+\\/\t\r\v\f\n)?!-]";

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regexEmoticons);


            System.Text.RegularExpressions.MatchCollection matches = regex.Matches(ret);
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                ret += match.Value;
            }

            return(ret);
        }
Example #22
0
        public string Resolve(string input)
        {
            if (input.IndexOf("#") >= 0)
            {
                System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, @"\#\w+\#");
                string   sKey   = m.Value.Substring(1, m.Value.Length - 2);
                string[] values = this[sKey];

                if (values != null)
                {
                    input = System.Text.RegularExpressions.Regex.Replace(input, @"\#\w+\#", values[0]);
                }
            }
            if (input.IndexOf(@"..\") >= 0)
            {
                int    nFirst = input.IndexOf(@"..\");
                string sPath  = input.Remove(0, nFirst);

                System.Text.RegularExpressions.MatchCollection ms = System.Text.RegularExpressions.Regex.Matches(
                    sPath, @"[.][.]\\");

                sPath = sPath.Replace(@"..\", "");
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);
                for (int i = 0; i < ms.Count; i++)
                {
                    di = di.Parent;
                }

                input = input.Substring(0, nFirst) + di.FullName;
            }
            return(input);
        }
Example #23
0
        /// <summary>
        /// Вспомогательный метод для парсинга, в котором определяется, какой список заполнять.
        /// </summary>
        /// <param name="collectionResults"> Список полученных значений с сайта. </param>
        /// <param name="ID"> Уникальный идентификатор валюты, для которой производится парсинг. </param>
        private void ParseHelper(System.Text.RegularExpressions.MatchCollection collectionResults, Tuple <string, CurrencyType> ID)
        {
            var list = new List <decimal>();

            foreach (var e in collectionResults)
            {
                list.Add(Decimal.Parse(e.ToString().Substring(4, 7)));
            }
            switch (ID.Item2)
            {
            case CurrencyType.USD:
            {
                listUSD = list;
                break;
            }

            case CurrencyType.EUR:
            {
                listEUR = list;
                break;
            }

            case CurrencyType.CNY:
            {
                listCNY = list.Select(t => t > 30 ? t / 10 : t).ToList();
                break;
            }

            default: throw new ArgumentException();
            }
        }
        internal static string FixJSON(string JSON)
        {
            /*
             * chart.opts =
             * {"title":"Company Sales/Expenses","colors":['#FF0000','#008000','#0000FF','#FFA500'],
             * "animation":{"duration":1000,"easing":"out"},"hAxis":{"textPosition":"default","title":"Hoz Axis Title","slantedText":true,"viewWindowMode":"default"}};
             *
             * all options with "title": or "xxxxx": => xxxxx:
             */

            System.Text.RegularExpressions.Regex           rxfix = new System.Text.RegularExpressions.Regex("\"\\w.+?\":.", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
            System.Text.RegularExpressions.MatchCollection mc    = rxfix.Matches(JSON);

            foreach (System.Text.RegularExpressions.Match m in mc)
            {
                string replace     = m.Value;
                string replacewith = string.Empty;
                // strip first '"'
                if (m.Value.StartsWith("\""))
                {
                    replacewith = m.Value.TrimStart('"');
                }
                if (m.Value.Contains("\":"))
                {
                    replacewith = replacewith.Replace("\":", ":");
                }

                JSON = JSON.Replace(replace, replacewith);
            }

            return(JSON);
        }
Example #25
0
        private int getNumNewLines(string s1)
        {
            string pattern = "\n";

            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(s1, pattern);
            return(matches.Count);
        }
        public int Detectpattern(String input, ref String valuse)  // 전화번호를 포함하고 있는 파일 추출
        {
            String[] patterns =
            {
                @"(^|\W)01[01]\d{7,8}(\W|$)",
                @"(^|\W)01[01]-\d{3,4}-\d{4}(\W|$)",
                @"((\w+\.)*\w+@(\w+\.)+[A-Za-z]+)",
                @"([0-9]{6}-[0-9]{7})",
                @"([0-9][0-9][01][0-9][0123][0-9]-[1234][0-9]{6})"
            };
            int count = 0;

            foreach (String pattern in patterns)
            {
                System.Text.RegularExpressions.MatchCollection matches =
                    System.Text.RegularExpressions.Regex.Matches(input, pattern);

                foreach (System.Text.RegularExpressions.Match m in matches)
                {
                    ++count;
                    valuse += m + "\n";
                }
            }
            return(count);
        }
        public static String ApplyRegex(String source, Sync.Direction direction)
        {
            String retStr = source ?? "";

            if (Settings.Instance.Obfuscation.Enabled && direction.Id == Settings.Instance.Obfuscation.Direction.Id)
            {
                foreach (DataGridViewRow row in Forms.Main.Instance.dgObfuscateRegex.Rows)
                {
                    DataGridViewCellCollection cells = row.Cells;
                    if (cells[Obfuscate.findCol].Value != null)
                    {
                        System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(
                            cells[Obfuscate.findCol].Value.ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                        System.Text.RegularExpressions.MatchCollection matches = rgx.Matches(retStr);
                        if (matches.Count > 0)
                        {
                            log.Debug("Regex has matched and altered string: " + cells[Obfuscate.findCol].Value.ToString());
                            if (cells[Obfuscate.replaceCol].Value == null)
                            {
                                cells[Obfuscate.replaceCol].Value = "";
                            }
                            retStr = rgx.Replace(retStr, cells[Obfuscate.replaceCol].Value.ToString());
                        }
                    }
                }
            }
            return(retStr);
        }
Example #28
0
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            string sourceValue = e.WebTest.Context[this.inputContextParameter].ToString();

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(this.regexText);

            //this option is potentially expensive from a computational standpoint.
            if (this.pickRandomMatch)
            {
                System.Text.RegularExpressions.MatchCollection matches = regex.Matches(sourceValue);
                int matchcount = matches.Count;
                if (matchcount > 0)
                {
                    AddToContext(e, matches[randomNumber.Next(0, matchcount)].Value);
                }
                else
                {
                    throw new ArgumentException("Could not find regex in existing context parameter " + this.inputContextParameter);
                }
            }

            //this option is cheaper.
            else
            {
                System.Text.RegularExpressions.Match match = regex.Match(sourceValue);
                if (match.Success)
                {
                    AddToContext(e, match.Value);
                }
                else
                {
                    throw new ArgumentException("Could not find regex in existing context parameter " + this.inputContextParameter);
                }
            }
        }
Example #29
0
        /// <summary>
        /// 正则查找
        /// </summary>
        /// <param name="reString">正文</param>
        /// <param name="regexCode">正则表达式</param>
        /// <returns>返回结果(单条数据)</returns>
        public static string GetRegexStr(string reString, string regexCode)
        {
            try
            {
                System.Text.RegularExpressions.Regex reg;                                  //正则表达式变量
                reg = new System.Text.RegularExpressions.Regex(regexCode);                 //初始化正则对象

                System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString); //匹配;
                string temp = string.Empty;                                                //声明一个临时变量
                for (int ic = 0; ic < mc.Count; ic++)
                {
                    System.Text.RegularExpressions.GroupCollection     gc = mc[ic].Groups;//获取所有分组
                    System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();
                    for (int i = 0; i < gc.Count; i++)
                    {
                        temp = gc[i].Value;  //得到组对应数据
                    }
                }
                return(temp);
            }
            catch
            {
                TextAdditional("正则查找失败");
                return(string.Empty);
            }
        }
Example #30
0
        public static int GetPageCount(string pdfPath)
        {
            try
            {
                byte[] buffer = File.ReadAllBytes(pdfPath);

                int length = buffer.Length;

                if (buffer == null)
                {
                    return(-1);
                }

                if (buffer.Length <= 0)
                {
                    return(-1);
                }

                string pdfText = Encoding.Default.GetString(buffer);

                System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");

                System.Text.RegularExpressions.MatchCollection matches = rx1.Matches(pdfText);

                return(matches.Count);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #31
0
        private void WebPageLoadedSearchCalled(object sender, WebPage.WebPageArguments args)
        {
            string htmlData = webpage.htmlData;
            if (htmlData != null)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(_regexPattern);
                results = regex.Matches(htmlData);

            }
            if(InfoReady != null)
            {
                InfoReady(this, new InfoReadyEventArgs("info ready"));
            }

               // webpage.WebPageLoaded -= WebPageLoadedSearchCalled;
        }
        /// <summary>
        /// リーダーの初期化
        /// </summary>
        public RegstoryHandler()
        {
            if (sizeKey1.ValueCount != 0)
            {
                // 画像の大きさ
                {
                    string s1 = sizeKey1.GetValue("sizeKey1").ToString();
                    mc = System.Text.RegularExpressions.Regex.Matches(s1, @"(Width=)(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        width = m.Value;
                        width = width.Replace("Width=", "");
                    }
                    size1.Width = int.Parse(width);
                    mc = System.Text.RegularExpressions.Regex.Matches(s1, @"(Height=)(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        height = m.Value;
                        height = height.Replace("Height=", "");
                    }
                    size1.Height = int.Parse(height);
                }
                // 画像の左上の位置
                {
                    string s2 = sizeKey1.GetValue("pictureTopLeft").ToString();
                    string X = "";
                    mc = System.Text.RegularExpressions.Regex.Matches(s2, @"(X=)(\d+)|(X=)\-(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        X = m.Value;
                        X = X.Replace("X=", "");
                    }
                    pictureTopLeft.X = int.Parse(X);
                    string Y = "";
                    mc = System.Text.RegularExpressions.Regex.Matches(s2, @"(Y=)(\d+)|(Y=)\-(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        Y = m.Value;
                        Y = Y.Replace("Y=", "");
                    }
                    pictureTopLeft.Y = int.Parse(Y);
                }
                // 画像のズーム
                {
                    string s3 = sizeKey1.GetValue("pictureZoom").ToString();
                    pictureZoom = double.Parse(s3) / 100;
                }
                // 画像の保存場所
                {
                    destination = sizeKey1.GetValue("destination").ToString();
                }
                // 自動保存
                {
                    autosave = sizeKey1.GetValue("autosave").ToString() == "True";
                }
                // メインフォームの表示位置
                {
                    string s3 = sizeKey1.GetValue("location").ToString();
                    string X = "";
                    mc = System.Text.RegularExpressions.Regex.Matches(s3, @"(X=)(\d+)|(X=)\-(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        X = m.Value;
                        X = X.Replace("X=", "");
                    }
                    location.X = int.Parse(X);
                    string Y = "";
                    mc = System.Text.RegularExpressions.Regex.Matches(s3, @"(Y=)(\d+)|(Y=)\-(\d+)");
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        Y = m.Value;
                        Y = Y.Replace("Y=", "");
                    }
                    location.Y = int.Parse(Y);
                }
            }
            else
            {
                size1 = defaultSize1;
                Size1 = size1;

                pictureTopLeft = new Point(0, 0);
                PictureTopLeft = pictureTopLeft;

                pictureZoom = 1d;
                PictureZoom = pictureZoom;

                destination = "";
                Destination = destination;

                autosave = true;
                Autosave = autosave;

                location = new Point(0, 0);
                Location = location;
            }
            if (sizeKey2.ValueCount != 0)
            {
                string s = sizeKey2.GetValue("sizeKey2").ToString();
                mc = System.Text.RegularExpressions.Regex.Matches(s, @"(Width=)(\d+)");
                foreach (System.Text.RegularExpressions.Match m in mc)
                {
                    width = m.Value;
                    width = width.Replace("Width=", "");
                }
                size2.Width = int.Parse(width);
                mc = System.Text.RegularExpressions.Regex.Matches(s, @"Height=\d+");
                foreach (System.Text.RegularExpressions.Match m in mc)
                {
                    height = m.Value;
                    height = height.Replace("Height=", "");
                }
                size2.Height = int.Parse(height);
            }
            else
            {
                size2 = defaultSize2;
                Size2 = size2;
            }
        }