Matches() public method

public Matches ( string input ) : System.Text.RegularExpressions.MatchCollection
input string
return System.Text.RegularExpressions.MatchCollection
Ejemplo n.º 1
2
		public static string UpdateStatus(string status, TwUser user, string replyId)
		{
			Regex regex = new Regex(@"\[(.*?)\]");
			List<FileInfo> media = new List<FileInfo>();
			foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
			{
				status = status.Replace(match.Value, "");
				FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
				if (!file.Exists)
					throw new FileNotFoundException("File not found", file.FullName);
				media.Add(file);
            }

			if (media.Count > 4) //limited by the twitter API
				throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");

			if (user == null)
				user = TwUser.LoadCredentials();
			string encodedStatus = Util.EncodeString(status);
			
			if (media.Count == 0)
				return InternalUpdateStatus(user, encodedStatus, replyId);
			else
				return InternalUpdateWithMedia(user, encodedStatus, replyId, media);
		}
 private IEnumerable<string> LoadProjects(
     string solutionPath)
 {
     const string projectRegEx = "Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\"";
     var content = File.ReadAllText(solutionPath);
     var projReg = new Regex(projectRegEx, RegexOptions.Compiled);
     var matches = projReg.Matches(content).Cast<Match>();
     var projects = matches.Select(x => x.Groups[2].Value).ToList();
     for (var i = 0; i < projects.Count; ++i)
     {
         if (!Path.IsPathRooted(projects[i]))
         {
             var folderName = Path.GetDirectoryName(solutionPath);
             if (folderName != null)
                 projects[i] = Path.Combine(folderName, projects[i]);
         }
         try
         {
             projects[i] = Path.GetFullPath(projects[i]);
         }
         catch (NotSupportedException ex)
         {
             resolver_ProgressMessageEvent($"Path: {projects[i]}, Error: {ex.Message}");
         }
     }
     return projects;
 }
Ejemplo n.º 3
1
        /// <summary>
        /// Обрабатывает шаблон, вставляет значение полей моделей в макросы в шаблоне
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        protected override string Process(string content)
        {
            // Подгатавливаем данные
            var parseRegEx = new Regex(@"\$\{([A-Za-z0-9]+?)\}");
            var sb = new StringBuilder(content);

            var ti = Model.GetType();

            // Находим все вхождения макросов по регулярному выражению
            var matches = parseRegEx.Matches(content);
            foreach (Match match in matches)
            {
                var propertyName = match.Groups[1].Value;

                // Ищем свойство у модели
                var propertyInfo = ti.GetProperty(propertyName);
                if (propertyInfo == null)
                {
                    // Похоже что данное свойство у модели не найдено
                    continue;
                }
                var value = propertyInfo.GetValue(Model,null);

                // Выполняем замену
                sb.Replace(match.Value, value != null ? value.ToString() : String.Empty);
            }

            // Отдаем преобразованный результат
            return sb.ToString();
        }
Ejemplo n.º 4
1
 public int RowCount(string source)
 {
   Regex rowRegex = new Regex(_rowDelimiter);
   _source = source;
   _rows = rowRegex.Matches(_source);
   return _rows.Count;
 }
Ejemplo n.º 5
1
 public void ShouldRegexMatchColonTerminatedFirstMultilineSlashNTerminated()
 {
   string content = string.Format("blah:{0}blah", "\n");
   Regex regex = new Regex(".*:$", RegexOptions.Multiline);
   regex.IsMatch(content).Should().BeTrue();
   regex.Matches(content).Count.Should().Be(1);
 }
Ejemplo n.º 6
1
        /// <summary>
        /// Corrects the image path relative to the requested page or css where they originate from
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestPath"></param>
        /// <returns></returns>
        public static string CorrectUrl(string url, string requestPath)
        {
            var correctedImgPath = url.TrimStart('~');

            // make sure 'requestPath' starts with a '/'
            if (!requestPath.StartsWith("/"))
                requestPath = "/" + requestPath;

            if (!url.StartsWith("/") && !url.StartsWith("../"))
            {
                correctedImgPath = VirtualPathUtility.GetDirectory(requestPath) + url.TrimStart('/');
            }
            else if (url.StartsWith("../"))
            {
                var path = VirtualPathUtility.GetDirectory(requestPath);
                var regex = new Regex(@"\.\./");
                var levelUpMatches = regex.Matches(url);
                var numberOfLevelsUp = levelUpMatches.Count;
                var pathDirs = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                var newPathDirs = pathDirs.Take(pathDirs.Length - numberOfLevelsUp);
                var newPath = String.Join("/", newPathDirs).Trim();
                correctedImgPath = regex.Replace(url, "");
                correctedImgPath = String.IsNullOrEmpty(newPath) ? String.Format("/{0}", correctedImgPath) : String.Format("/{0}/{1}", newPath, correctedImgPath);
            }

            return correctedImgPath;
        }
Ejemplo n.º 7
0
        public override void ProcessInStream(List<TOBEntityBase> inStreamList)
        {
            Regex regx = new Regex("https?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

            foreach (TOBEntityBase tobEB in inStreamList)
            {
                if (tobEB.GetType() == typeof(Status))
                {
                    Status tempVar = (Status)tobEB;

                    MatchCollection matches = regx.Matches(tempVar.Text);

                    foreach (Match match in matches)
                    {
                        Uri webLink = new Uri(match.Value);

                        AddControlToPanel(CreateWebPreviewControl(tempVar.UserProfile.ScreenName, webLink));
                    }
                }

                if (tobEB.GetType() == typeof(DirectMessage))
                {
                    DirectMessage tempDM = (DirectMessage)tobEB;
                    MatchCollection matchesDM = regx.Matches(tempDM.Text);
                    foreach (Match match in matchesDM)
                    {
                        Uri webLink = new Uri(match.Value);
                        AddControlToPanel(CreateWebPreviewControl(tempDM.UserProfile.ScreenName,webLink));
                    }
                }
            }

            return;
        }
Ejemplo n.º 8
0
        public static void NumericalSort(string[] ar)
        {
            Regex rgx = new Regex("([^0-9]*)([0-9]+)");
            Array.Sort(ar, (a, b) =>
            {
                var ma = rgx.Matches(a);
                var mb = rgx.Matches(b);

                // KBR 20150209 'CH' and 'Ch'
                // KBR 20140907 might not be numeric!
                if (ma.Count != mb.Count)
                    return string.Compare(a, b, StringComparison.OrdinalIgnoreCase);

                for (int i = 0; i < ma.Count; ++i)
                {
                    int ret = String.Compare(ma[i].Groups[1].Value, mb[i].Groups[1].Value, StringComparison.OrdinalIgnoreCase);
                    if (ret != 0)
                        return ret;

                    // KBR 20141222 integer overflow
                    ret = (int)(long.Parse(ma[i].Groups[2].Value) - long.Parse(mb[i].Groups[2].Value));
                    if (ret != 0)
                        return ret;
                }

                return 0;
            });
        }
        public static string XFilterInclude(this string @string, string pattern)
        {
            if (string.Equals(@string, null))
            {
                return null;
            }

            if (string.Equals(@string, string.Empty))
            {
                return string.Empty;
            }

            var stringBuilder = new StringBuilder();
            var regEx = new Regex(pattern);

            // Check to see if their are no matching characters.
            if (regEx.Matches(@string).Count == 0)
            {
                return @string;
            }

            foreach (Match match in regEx.Matches(@string))
            {
                if (match.Value != string.Empty)
                {
                    stringBuilder.Append(match.Value);
                }
            }

            return stringBuilder.ToString();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// ͨ��������ʽ��ȡxml�б�ע���ֶ�
        /// ��עʾ�� [field_name]
        /// </summary>
        /// <param name="p_strObject">��������</param>
        /// <returns>�ֶμ���</returns>
        public static List<string> GetFieldFromXmlObject(string p_strObject)
        {
            List<string> _listField = new List<string>();
            Regex reg = new Regex(@"\[[^\[^\]]*\]");
            string _strXml = GetXML(p_strObject);
            int _nCount = reg.Matches(_strXml).Count;
            for (int i = 0; i < _nCount; i++)
            {
                string _strField = reg.Matches(_strXml)[i].Captures[0].Value;
                if (_strField.ToUpper().StartsWith("[COL"))
                {
                    continue;
                }
                _listField.Add(_strField);
            }
            reg = new Regex(@"\{[^\{^\}]*\}");
            //string _strXml = GetXML(p_strObject);
            _nCount = reg.Matches(_strXml).Count;
            for (int i = 0; i < _nCount; i++)
            {
                string _strValue = reg.Matches(_strXml)[i].Captures[0].Value;
                //if (_strValue.g)
                //{

                //}
                _listField.Add(_strValue);
            }
            return _listField;
        }
Ejemplo n.º 11
0
        public ActionResult SCPartners()
        {
            wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
            // Loading model into view
            LinkedInModels lim = new LinkedInModels();

            string data = wc.DownloadString("http://www.sitecore.net/partners.aspx");
            int startIndex = data.IndexOf("<ul class=\"partner-links\">");
            data = data.Substring(startIndex, data.Length - (startIndex + 1));
            data = data.Substring(0, data.IndexOf("</ul>") + 5);

            XmlDocument doc = new XmlDocument();
            doc.Load(new StringReader(data));

            XmlNodeList nodes = doc.SelectNodes("//li");
            List<string> partnerList = new List<string>();
            foreach (XmlNode node in nodes)
            {
                string partnerLink = "http://www.sitecore.net/partners/find-partner.aspx?@partnertype={{{0}}}#s=~_d0!2!1!!1!6!0!1!!2!!!2!1!0!_d2!4!764!W.+Europe+Standard+Time!%7B43ECEB4F-C3A3-4328-9BF8-7A1240818CC8%7D!%7B{0}%7D!_d6!HrFrsrErGrsryqIqxpuspvpwpDpBputpvpvpqAqxpuspvpwpCpzputpvpvpqqryqqqrsr!fvf%7C%40partnertype!_d0!3!Partners!_d8!fvf%7C%40country!{0}!_d1!43ECEB4F-C3A3-4328-9BF8-7A1240818CC8!!xqIqtGpypupvppwpupwpvppHpppwpupJpMpNpKpLpBpCpvpzpApDpFppEpqxpyprpqsq!";
                Regex regParterData = new Regex("{(.*)}");
                string partnerGuid = regParterData.Match(node.SelectSingleNode("//a").Attributes.GetNamedItem("href").Value).Value.Replace("{", "").Replace("}", "");
                partnerLink = string.Format(partnerLink, partnerGuid);

                byte[] partnerData = wc.DownloadData(new Uri(partnerLink));

                    Regex re = new Regex(@"<div class=""partner-result"">\s*(.+?)</a>\s*</div>", RegexOptions.Singleline);

                    string temp = System.Text.Encoding.UTF8.GetString(partnerData);

                    int count = re.Matches(System.Text.Encoding.UTF8.GetString(partnerData)).Count;

                    foreach (Match match in re.Matches(System.Text.Encoding.UTF8.GetString(partnerData)))
                    {
                        string tempPartnerData = match.Value;

                        //XmlDocument partnerDoc = new XmlDocument();
                        //Regex rePartner = new Regex("<div class=\"partner-img\">(.*)</div>", RegexOptions.Singleline);
                        //string partnerImage = rePartner.Match(tempPartnerData).Value;
                        //rePartner = new Regex("<div class=\"details\">(.*)</div>", RegexOptions.Singleline);
                        //string partnerDetails = rePartner.Match(tempPartnerData).Value;
                        //rePartner = new Regex("<a(.*)</a>", RegexOptions.Singleline);
                        //string partnerLink = rePartner.Match(tempPartnerData).Value;

                        //string partnerDescription = rePartner.Match(tempPartnerData).Value;
                        if (!partnerList.Contains(tempPartnerData))
                        {
                            partnerList.Add(tempPartnerData);
                        }
                    }
            }
            wc.DownloadDataCompleted -= new DownloadDataCompletedEventHandler(DownloadCompleted);

            List<string> gyutyutyut = partnerList;

            return View("LinkedIn", lim.Person);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// ͨ��������ʽ��ȡxml�б�ע���ֶ�
 /// ��עʾ�� [field_name]
 /// </summary>
 /// <param name="p_strObject">��������</param>
 /// <returns>�ֶμ���</returns>
 public static List<string> GetFieldFromXml(string p_strObject)
 {
     List<string> _listField = new List<string>();
     Regex reg = new Regex(@"\[[^\[^\]]*\]");
     string _strXml = GetXML(p_strObject);
     int _nCount = reg.Matches(_strXml).Count;
     for (int i = 0; i < _nCount; i++)
     {
         _listField.Add(reg.Matches(_strXml)[i].Captures[0].Value);
     }
     return _listField;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// 获取图片标志
 /// </summary>
 private string[] GetImgTag(string htmlStr)
 {
     Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
     string[] strAry = new string[regObj.Matches(htmlStr).Count];
     int i = 0;
     foreach (Match matchItem in regObj.Matches(htmlStr))
     {
         strAry[i] = GetImgUrl(matchItem.Value);
         i++;
     }
     return strAry;
 }
Ejemplo n.º 14
0
 public string compress(string originalMessage)
 {
     string pattern = @"[aeiouAEIOU]";
     Regex r = new Regex(pattern);
     List<string> list = new List<string>();
     foreach (string s in originalMessage.Split(' '))
     {
         if (s != "")
             list.Add(s);
     }
     for (int i = 0; i < list.Count; i++)
     {
         string t1 = list[i];
         int x = r.Matches(list[i]).Count;
         if (x != list[i].Length)
         {
             int j = 0;
             string temp = "";
             string temp1 = "";
             List<string> values = new List<string>();
             List<int> indices = new List<int>();
             foreach (Match m in r.Matches(list[i]))
             {
                 values.Add(m.Value);
                 indices.Add(m.Index);
             }
             for (int b = 0; b < indices.Count; b++)
             {
                 if (indices[b] == j)
                 {
                     temp1 += values[b];
                     j++;
                 }
             }
             j = list[i].Length - 1;
             for (int a = indices.Count - 1; a >= 0; a--)
             {
                 if (indices[a] == j)
                 {
                     temp = temp.Insert(0, values[a]);
                     j--;
                 }
             }
             for (int a = 0; a < values.Count; a++)
                 list[i] = list[i].Replace(values[a], "");
             list[i] = list[i].Insert(list[i].Length, temp);
             list[i] = list[i].Insert(0, temp1);
             originalMessage = originalMessage.Replace(t1, list[i]);
         }
     }
     return originalMessage;
 }
Ejemplo n.º 15
0
 void ExtractName(string input, string match)
 {
     Regex m = new Regex(Formatter.extractWikiNamesString);
     if (match != null)
     {
         Assert.AreEqual(1, m.Matches(input).Count, match);
         Assert.AreEqual(match, m.Matches(input)[0].Groups["topic"].Value, match);
     }
     else
     {
         Assert.AreEqual(0, m.Matches(input).Count, match);
     }
 }
Ejemplo n.º 16
0
        public bool FindStringInFields(string text)
        {
            Regex rx = new Regex(text, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            MatchCollection matchesName = rx.Matches(this.Name);
            MatchCollection matchesURL = rx.Matches(this.URL);
            MatchCollection matchesLogin = rx.Matches(this.Login);
            MatchCollection matchesPassword = rx.Matches(this.Password);

            if (matchesName.Count > 0 || matchesURL.Count > 0 || matchesLogin.Count > 0 || matchesPassword.Count > 0)
                return true;

            return false;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 获取图片标志
        /// </summary>
        private string[] GetImgTag(string htmlStr)
        {
            System.Text.RegularExpressions.Regex regObj = new System.Text.RegularExpressions.Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            string[] strAry = new string[regObj.Matches(htmlStr).Count];
            int      i      = 0;

            foreach (Match matchItem in regObj.Matches(htmlStr))
            {
                strAry[i] = GetImgUrl(matchItem.Value);
                i++;
            }
            return(strAry);
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Regex regex = new Regex(@"(?<=\bdouble\s)(\w+)");
            MatchCollection doubles = regex.Matches(input);
            Regex regexint = new Regex(@"(?<=\bint\s)(\w+)");
            MatchCollection ints = regexint.Matches(input);

            var integers=new List<string>();
            var doublers=new List<string>();

            while (input != "//END_OF_CODE")
            {

                doubles = regex.Matches(input);
                ints = regexint.Matches(input);

                foreach (Match p in doubles)
                {
                    doublers.Add(p.ToString());
                }
                foreach (Match q in ints)
                {
                    integers.Add(q.ToString());
                }
                input = Console.ReadLine();
            }
            doublers.Sort();
            integers.Sort();
            if (doublers.Count==0&&integers.Count==0)
            {
                Console.WriteLine("Doubles: None");
                Console.WriteLine("Ints: None");
            }
            else if(doublers.Count==0)
            {
                Console.WriteLine("Doubles: None");
                Console.WriteLine("Ints: " + string.Join(", ", integers));
            }
            else if(integers.Count==0)
            {
                Console.WriteLine("Ints: None");
                Console.WriteLine("Doubles: "+string.Join(", ",doublers));
            }
            else
            {
             Console.WriteLine("Doubles: "+string.Join(", ",doublers));
             Console.WriteLine("Ints: " + string.Join(", ", integers));
            }
        }
        private Dictionary<string, List<Session>> GetGroupedSet(IEnumerable<Session> sessionList)
        {
            Regex regex = new Regex(@"\w");
            var groupedResult = (from s in sessionList
                                 group s by regex.Matches(s.Title)[0].Value into GroupedSessions
                                 select new
                                            {
                                                Key = GroupedSessions.Key,
                                                Value = GroupedSessions
                                            });

            var resultDictionary = groupedResult
                .ToDictionary(kv => kv.Key, kv => kv.Value.OrderBy(s => regex.Matches(s.Title)[0].Value).ToList());
            return CondenseNumerics(resultDictionary);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Replaces all instances of a 'key' (e.g. {foo} or {foo:SomeFormat}) in a string with an optionally formatted value, and returns the result.
        /// </summary>
        /// <param name="formatString">The string containing the key; unformatted ({foo}), or formatted ({foo:SomeFormat})</param>
        /// <param name="key">The key name (foo)</param>
        /// <param name="replacementValue">The replacement value; if null is replaced with an empty string</param>
        /// <returns>The input string with any instances of the key replaced with the replacement value</returns>
        public static string InjectSingleValue(this string formatString, string key, object replacementValue)
        {
            var result = formatString;

            //regex replacement of key with value, where the generic key format is:
            //Regex foo = new Regex("{(foo)(?:}|(?::(.[^}]*)}))");
            var attributeRegex = new Regex("{(" + key + ")(?:}|(?::(.[^}]*)}))"); //for key = foo, matches {foo} and {foo:SomeFormat}

            //loop through matches, since each key may be used more than once (and with a different format string)
            foreach (Match m in attributeRegex.Matches(formatString))
            {
                string replacement;
                if (m.Groups[2].Length > 0)
                {
                    //do a double string.Format - first to build the proper format string, and then to format the replacement value
                    var attributeFormatString = string.Format(CultureInfo.InvariantCulture, "{{0:{0}}}", m.Groups[2]);
                    replacement = string.Format(CultureInfo.CurrentCulture, attributeFormatString, replacementValue);
                }
                else
                {
                    replacement = (replacementValue ?? string.Empty).ToString();
                }

                //perform replacements, one match at a time
                result = result.Replace(m.ToString(), replacement); //attributeRegex.Replace(result, replacement, 1);
            }

            return(result);
        }
Ejemplo n.º 21
0
        public static Basket parsedata(string data, bool onlylinked, bool verify, DebugDelegate d)
        {
            debs = d;
            Basket b = new BasketImpl();

            if (onlylinked)
            {
                Basket b2 = LinkedOnlyNASDAQ(data);
                if (b2.Count > 0)
                {
                    b.Add(b2);
                }
                Basket b3 = LinkedOnlyNYSE(data);
                if (b3.Count > 0)
                {
                    b.Add(b3);
                }
            }
            else
            {
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"[A-Z.]{1,6}");
                foreach (System.Text.RegularExpressions.Match m in r.Matches(data))
                {
                    b.Add(m.Value);
                }
            }
            return(verify_equitysymbol(b, verify, d));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// To convert a string to a phone number.
        /// </summary>
        /// <param name="phoneNumberString">Input string</param>
        /// <returns>Phone number as string</returns>
        public static string ToPhoneNumber(this string phoneNumberString)
        {
            if (string.IsNullOrEmpty(phoneNumberString))
            {
                return(string.Empty);
            }

            var             numberPattern = new System.Text.RegularExpressions.Regex("\\d+");
            MatchCollection numberStrips  = numberPattern.Matches(phoneNumberString);

            if (numberStrips.Count < 1)
            {
                return(string.Empty);
            }

            StringBuilder phoneNumber = new StringBuilder();

            foreach (Match strip in numberStrips)
            {
                phoneNumber.Append(strip.Value);
            }

            if (phoneNumber.Length > 6)
            {
                phoneNumber.Insert(6, " ");
            }

            if (phoneNumber.Length > 3)
            {
                phoneNumber.Insert(3, " ");
            }

            return(phoneNumber.ToString());
        }
Ejemplo n.º 23
0
        public static List <string> ExtractBindVariables(string sql)
        {
            List <string> result;

            lock (DatabaseUtilities._bindVariables.SyncRoot)
            {
                List <string> parameters = DatabaseUtilities._bindVariables[sql] as List <string>;
                if (parameters == null)
                {
                    parameters = new List <string>();
                    string sqlWithoutGlobals = sql.Replace("@@", string.Empty);
                    System.Text.RegularExpressions.Regex           regex   = new System.Text.RegularExpressions.Regex("[@:]\\w+([, )\\r\\n]|$)");
                    System.Text.RegularExpressions.MatchCollection matches = regex.Matches(sqlWithoutGlobals);
                    foreach (System.Text.RegularExpressions.Match match in matches)
                    {
                        parameters.Add(System.Text.RegularExpressions.Regex.Replace(match.Value, "[, )\r\n]", string.Empty));
                    }
                    parameters.Remove("@InternalNewId");
                    parameters.Remove(":InternalNewId");
                    DatabaseUtilities._bindVariables[sql] = parameters;
                }
                result = parameters;
            }
            return(result);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Create <see cref="NewFolding"/>s for the specified document.
        /// </summary>
        public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
        {
            var newFoldings = new List<NewFolding>();

            var template = FoldingTemplates[0];
            var regexOpenFolding = new Regex(template.OpeningPhrase);
            var matchesOpenFolding = regexOpenFolding.Matches(document.Text);

            var regexCloseFolding = new Regex(template.ClosingPhrase);
            var matchesCloseFolding = regexCloseFolding.Matches(document.Text);

            var currentOpenIndex = 0;
            for (var i = 0; i < matchesCloseFolding.Count && currentOpenIndex < matchesOpenFolding.Count; i++)
            {
                if (matchesOpenFolding[currentOpenIndex].Index >= matchesCloseFolding[i].Index)
                    continue;
                var folding = new NewFolding(matchesOpenFolding[currentOpenIndex].Index + 1,
                    matchesCloseFolding[i].Index + 10)
                {
                    DefaultClosed = template.IsDefaultFolded,
                    Name = template.Name
                };
                newFoldings.Add(folding);
                while (currentOpenIndex < matchesOpenFolding.Count &&
                    matchesOpenFolding[currentOpenIndex].Index < matchesCloseFolding[i].Index)
                {
                    currentOpenIndex++;
                }
            }
            return newFoldings;
        }
Ejemplo n.º 25
0
        public static String FixAlexa(String timezone)
        {
            //Alexa (Amazon Echo) is a bit dumb - she creates Google Events with a GMT offset "timezone". Eg GMT-5
            //This isn't actually a timezone at all, but an area, and not a legal IANA value.
            //So to workaround this, we'll turn it into something valid at least, by inverting the offset sign and prefixing "Etc\"
            //Issues:-
            // * As it's an area, Microsoft will just guess at the zone - so GMT-5 for CST may end up as Bogata/Lima.
            // * Not sure what happens with half hour offset, such as in India with GMT+4:30
            // * Not sure what happens with Daylight Saving, as zones in the same area may or may not follow DST.

            try {
                System.Text.RegularExpressions.Regex           rgx     = new System.Text.RegularExpressions.Regex(@"^GMT([+-])(\d{1,2})(:\d\d)*$");
                System.Text.RegularExpressions.MatchCollection matches = rgx.Matches(timezone);
                if (matches.Count > 0)
                {
                    log.Debug("Found an Alexa \"timezone\" of " + timezone);
                    String fixedTimezone = "Etc/GMT" + (matches[0].Groups[1].Value == "+" ? "-" : "+") + Convert.ToInt16(matches[0].Groups[2].Value).ToString();
                    log.Debug("Translated to " + fixedTimezone);
                    return(fixedTimezone);
                }
            } catch (System.Exception ex) {
                log.Error("Failed to detect and translate Alexa timezone.");
                OGCSexception.Analyse(ex);
            }
            return(timezone);
        }
        public void ProcessCoursesStrings(string coursesString, Dictionary<string, decimal> coursesCatalog, ref List<string> coursesList)
        {
            coursesString = Regex.Replace(coursesString, "(([ ]){3,}) ", Environment.NewLine);
            coursesString = Regex.Replace(coursesString, "\n", Environment.NewLine);
            coursesList = coursesString.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
            var courseRegex = new Regex(@".+:");
            var match = courseRegex.Match(coursesString);

            var isCannonicalCourse = new Regex(@"(?<=:).+\w");

            for(var ii=0; ii < coursesList.Count; ii++)
            {
                if(coursesList[ii] == "" || coursesList[ii] == " ")
                {
                    coursesList.RemoveAt(ii);
                    ii--;
                }
            }

            foreach (Match itemMatch in courseRegex.Matches(coursesString))
            {
                if (itemMatch.Value != "" && itemMatch.Value != " ")
                {
                    var x = itemMatch.Value.Replace(":", "");
                    var targetCourseLineDescription = coursesList.First(coursePointer => coursePointer.StartsWith(x) && coursePointer.IndexOf(x) < coursePointer.IndexOf(":"));

                    if (isCannonicalCourse.IsMatch(targetCourseLineDescription))
                        coursesCatalog.Add(itemMatch.Value.Replace(":", ""), -1);
                    else
                        coursesCatalog.Add(itemMatch.Value.Replace(":", ""), 0);
                }
            }
        }
Ejemplo n.º 27
0
        public void ParseTemplate(string templateContent)
        {
            templateContent = PreprocessTemplate(templateContent);
            //使用正则表达式来列出模板中所有可能的数据标签
            string regex = @"\$(\w+)(?:!(\w+))*\$";

            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                                                                   | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
            MatchCollection mc = reg.Matches(templateContent);

            foreach (Match m in mc)
            {
                if (m.Groups[1].Captures.Count > 0)
                {
                    string           tag = m.Groups[1].Value;
                    StringCollection sc  = DataLabels[tag] as StringCollection;
                    if (sc == null)
                    {
                        sc = new StringCollection();
                        DataLabels[tag] = sc;
                    }
                    foreach (Capture c in m.Groups[2].Captures)
                    {
                        string field = c.Value;
                        if (sc.IndexOf(field) < 0)
                        {
                            sc.Add(field);
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public TextMessage ExtractThread(TextMessage txtmsg, bool bUpdateMessageText)
        {
            System.Diagnostics.Debug.WriteLine("Original message: " + txtmsg.Message);

            System.Text.RegularExpressions.Regex           regex           = new System.Text.RegularExpressions.Regex(strThreadPattern);
            System.Text.RegularExpressions.MatchCollection matchCollection = regex.Matches(txtmsg.Message);

            if (matchCollection.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match match in matchCollection)
                {
                    if (match.Groups["threadName"] != null)
                    {
                        txtmsg.Thread = match.Groups["threadName"].Value;
                        txtmsg.Thread.Trim();
                        System.Diagnostics.Debug.WriteLine("Thread: " + txtmsg.Thread);
                    }
                    if (match.Groups["messageText"] != null)
                    {
                        if (bUpdateMessageText)
                        {
                            txtmsg.Message = match.Groups["messageText"].Value;
                            txtmsg.Message = txtmsg.Message.Trim();
                            System.Diagnostics.Debug.WriteLine("Message: " + txtmsg.Message);
                        }
                    }
                }
            }
            return(txtmsg);
        }
Ejemplo n.º 29
0
        public static string ToProperUrlEscape(this string stringToEscape)
        {
            if (string.IsNullOrEmpty(stringToEscape))
            {
                return null;
            }

            // URL encoding podľa Microsoftu
            var urlEncode = WebUtility.UrlEncode(stringToEscape);
            if (urlEncode != null)
            {
                var result = urlEncode.Replace("+", "%20");

                // lower-case -> upper-case
                var hexRegex = new Regex("%[0-9a-f]{2}", RegexOptions.IgnoreCase);
                var matches = hexRegex.Matches(result);

                result = matches.Cast<object>()
                    .Aggregate(result, (current, m) => current.Replace(m.ToString(), m.ToString().ToUpper()));

                // C# nekóduje (, ), $, !, * a "
                var notEncodedChars = new[] {"(", ")", "$", "!", "*", "\'"};
                result = notEncodedChars.Aggregate(result,
                    (current, c) => current.Replace(c, string.Format("%{0}", ((int) Convert.ToChar(c)).ToString("X"))));

                // tilda nesmie byť zakódovaná
                result = result.Replace("%7E", "~");

            }
            return string.Empty;
        }
Ejemplo n.º 30
0
 public static bool ContainsLightHex(this string text)
 {
     if (text.IsNullOrWhiteSpace())
     {
         return(false);
     }
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\[([a-fA-F0-9]{6})\\]");
     if (regex.IsMatch(text))
     {
         foreach (System.Text.RegularExpressions.Match match in regex.Matches(text))
         {
             if (LightHex(match.Groups[1].Value))
             {
                 bool result = true;
                 return(result);
             }
         }
     }
     System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex("\\#([a-fA-F0-9]{6})");
     if (regex2.IsMatch(text))
     {
         foreach (System.Text.RegularExpressions.Match match2 in regex2.Matches(text))
         {
             if (LightHex(match2.Groups[1].Value))
             {
                 bool result = true;
                 return(result);
             }
         }
     }
     return(false);
 }
Ejemplo n.º 31
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBox1.Text.Trim()))
            {
                MessageBox.Show("请先在文本中输入一个IP!");
                return;
            }
            var s   = webBrowser1.Document.Body.InnerHtml;;
            var reg = new System.Text.RegularExpressions.Regex("<tbody>(.*)<\\/tbody>");

            foreach (Match m in reg.Matches(s))
            {
                var xx = m.ToString();
                if (xx.Contains(textBox1.Text))
                {
                    Console.WriteLine(m);
                    var sbOut = new System.Text.StringBuilder();
                    sbOut.AppendLine(@"<html>");
                    sbOut.AppendLine("<table>" + m.ToString() + "</table>");
                    sbOut.AppendLine("</html");
                    var sFileTemplate = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "1.html");
                    var sOut          = System.IO.File.ReadAllText(sFileTemplate);
                    sOut = sOut.Replace("${SSTABLE}", "<table>" + m.ToString() + "</table>");
                    var sFileOut = getFilePath("2.html");
                    System.IO.File.WriteAllText(sFileOut, sOut);
                    ToSSRJson();

                    var _config = Configuration.Load();
                    Configuration.Save(_config);
                    controller.GetConfiguration();
                }
            }
            Console.WriteLine(s);
        }
Ejemplo n.º 32
0
        private void BindValues()
        {
            string sTo = emails;

            string regex = "([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\\w]*[0-9a-zA-Z])*\\.)+[a-zA-Z]" +
                           "{2,9})";
            List <string> dic = new List <string>();

            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                                                                   | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);


            foreach (Match item in reg.Matches(sTo))
            {
                if (!dic.Contains(item.Value))
                {
                    dic.Add(item.Value);
                }
            }
            string[] _mas = dic.ToArray();

            for (int i = 0; i < _mas.Length; i++)
            {
                lstSelected.Items.Add(new ListItem(_mas[i], _mas[i]));
            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), "_startValues", "SaveFields();", true);
        }
Ejemplo n.º 33
0
 static void Main(string[] args)
 {
     int cases = int.Parse(Console.ReadLine());
     string check = "abcdefghijklmnopqrstuvwxyz1234567890_";
     string[] sentences = new string[cases];
     for (int i = 0; i < cases; i++)
         sentences[i] = "-" + Console.ReadLine() + "-";
     int words = int.Parse(Console.ReadLine());
     for (int i = 0; i < words; i++)
     {
         int res = 0;
         string temp = Console.ReadLine();
         Regex r = new Regex(temp);
         for (int a = 0; a < sentences.Length; a++)
         {
             foreach (Match m in r.Matches(sentences[a]))
             {
                 if ((!check.Contains(sentences[a][m.Index - 1].ToString())) && (!check.Contains(sentences[a][m.Index + temp.Length].ToString())))
                     res++;
             }
         }
         Console.WriteLine(res);
     }
     Console.ReadLine();
 }
Ejemplo n.º 34
0
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            string username = ConvertMD5(textBoxAccount.Text);
            string password = ConvertSHA1(textBoxPassword.Text);

            try
            {
                System.Net.HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://bluesheepbot.com/c.php?mdp=" + username + password);

                System.Net.HttpWebResponse WebResponse = (System.Net.HttpWebResponse)WebRequest.GetResponse();
                System.IO.StreamReader     STR         = new System.IO.StreamReader(WebResponse.GetResponseStream());
                string ReadSource = STR.ReadToEnd();
                //MessageBox.Show(ReadSource);
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("Account" + "=(\\d+)");
                MatchCollection matches   = Regex.Matches(ReadSource);
                int             nbPremium = 0;
                foreach (Match match in matches)
                {
                    string[] RegSplit = match.ToString().Split('=');
                    nbPremium = Convert.ToInt32(RegSplit[1]);
                }
                mainfrm = new MainForm(version);
                mainfrm.Show();
                Hide();
            }
            catch (WebException exception)
            {
                MessageBox.Show("Echec de connexion. Vérifiez votre connexion :\n" + exception.Message);
            }
        }
Ejemplo n.º 35
0
        private string SetImages(string content)
        {
            foreach (Match m in m_ImgRegEx.Matches(content))
            {
                Match m2 = m_ImgSrcRegEx.Match(m.Value);
                if (m2.Success)
                {
                    string imgsrc = m2.Value.Remove(0, 5).Trim();
                    imgsrc = imgsrc.Remove(imgsrc.Length - 1, 1);
                    object s = Properties.Resources.ResourceManager.GetObject(imgsrc);
                    if (s != null)
                    {
                        string path = System.IO.Path.GetTempPath() + imgsrc;
                        if (s.GetType() == typeof(System.Drawing.Bitmap))
                        {
                            System.Drawing.Bitmap image = s as System.Drawing.Bitmap;

                            image.Save(path);
                            content = content.Replace(m2.Value, "src=\"file://" + path + "\" ");
                        }
                    }
                    else
                    {
                        content = content.Replace(m.Value, string.Empty);
                    }
                }
            }

            return(content);
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Find the numbe of tags in a given XML
 /// </summary>
 /// <param name="pb">Progress bar</param>
 /// <param name="sourcefile">Source XML File</param>
 public static void SetProgressBarValue(ProgressBar pb, string sourcefile)
 {
     if (pb == null) return;
     int setValue = 0;
     if (File.Exists(sourcefile))
     {
         var streamReader = new StreamReader(sourcefile);
         string text = string.Empty;
         try
         {
             //throw new System.OutOfMemoryException(" ");
             text = streamReader.ReadToEnd();
         }
         catch (OutOfMemoryException ex)
         {
             Console.Write(ex.Message);
         }
         streamReader.Close();
         var reg = new Regex("</", RegexOptions.Multiline);
         MatchCollection mat = reg.Matches(text);
         setValue = mat.Count;
     }
     pb.Minimum = 0;
     pb.Maximum = setValue;
     pb.Visible = true;
 }
Ejemplo n.º 37
0
        public void SetRouteParamsTest()
        {
            string endpoint = "/v1/accounts/:account_id/orders";
            Regex rx = new Regex("[:](\\S[^/]*)");
            MatchCollection matches = rx.Matches(endpoint);

            Dictionary<string, string> rps = new Dictionary<string, string>();
            rps.Add("account_id", "234234");

            Assert.IsTrue(matches.Count > 0);

            foreach (Match match in matches)
            {
                Assert.IsTrue(match.Groups.Count >= 2);
                foreach (KeyValuePair<string, string> routeParam in rps)
                {
                    if (match.Groups[1].Value == routeParam.Key)
                    {
                        endpoint = endpoint.Replace(match.Value, routeParam.Value);
                    }
                }
            }

            Assert.IsTrue(endpoint.Contains("234234"));
        }
Ejemplo n.º 38
0
        internal IEnumerable <EmoticonFindResult> Find(string str)
        {
            if (m_reg != null)
            {
                var matches = m_reg.Matches(str);
                foreach (Match match in matches)
                {
                    yield return(new EmoticonFindResult(this, match.Index, match.Length));
                }
            }
            else
            {
                int i = -1;

                while (i + Regex.Length <= str.Length)
                {
                    i = str.IndexOf(Regex, i + 1);
                    if (i == -1)
                    {
                        break;
                    }

                    yield return(new EmoticonFindResult(this, i, Regex.Length));
                }
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Unicode字符转汉字 允许自定义分隔字符
        /// </summary>
        /// <param name="str">需要转换的字符串</param>
        /// <param name="SplitString">分隔字符</param>
        /// <param name="TrimStr">如果有尾部数据则填写尾部</param>
        /// <returns>处理后结果</returns>
        public string FromUnicodeString(string str, string SplitString = "u", string TrimStr = ";")
        {
            string regexCode = SplitString == "u" ? "\\\\u(\\w{1,4})" : SplitString + "(\\w{1,4})";
            string reString  = str;

            System.Text.RegularExpressions.Regex           reg = new System.Text.RegularExpressions.Regex(regexCode);
            System.Text.RegularExpressions.MatchCollection mc  = reg.Matches(reString);
            for (int i = 0; i < mc.Count; i++)
            {
                try
                {
                    var outs = (char)int.Parse(mc[i].Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
                    if (str.IndexOf(mc[i].Groups[0].Value + TrimStr) > 0)
                    {
                        //如果出现(封号);结尾则连带符号替换
                        str = str.Replace(mc[i].Groups[0].Value + TrimStr, outs.ToString());
                    }
                    else
                    {
                        str = str.Replace(mc[i].Groups[0].Value, outs.ToString());
                    }
                }
                catch
                {
                    continue;
                }
            }
            return(str);
        }
Ejemplo n.º 40
0
        public List<ESPNGame> GetGames(int year, int seasonType, int weekNum)
        {
            var games = new List<ESPNGame>();
            Regex gameRX = new Regex("gameId=[0-9]+");
            var url = string.Format("{0}/{1}", GAME_URL, string.Format("_/year/{0}/seasontype/{1}/week/{2}", year.ToString(), seasonType.ToString(), weekNum.ToString()));
            var html = HelperMethods.LoadHtmlFromUrl(url);
            var gameIds = gameRX.Matches(html);

            foreach (Match gId in gameIds)
            {
                var gameId = System.Convert.ToInt32(gId.Value.Replace("gameId=", string.Empty));

                if (!games.Select(g => g.GameId).Contains(gameId))
                {
                    try
                    {
                        var teamsForGame = GetTeamsByGame(gameId);

                        ESPNGame game = new ESPNGame();
                        game.GameId = gameId;
                        game.HomeTeamId = teamsForGame["home"];
                        game.AwayTeamId = teamsForGame["away"];
                        games.Add(game);
                    }
                    catch { }
                }
            }

            return games.Distinct().ToList();
        }
Ejemplo n.º 41
0
 private static int GetSumOfInts(string input)
 {
     var regex = new Regex(@"(-?\d+)");
     var matches = regex.Matches(input).OfType<Match>().ToList();
     var sum = matches.Sum(x => int.Parse(x.Value));
     return sum;
 }
Ejemplo n.º 42
0
        static IEnumerable<string> GetLinks(string text)
        {
            var regex = new Regex(@"[a-zA-Z]+[ \t]*->[ \t]*[a-zA-Z]+[ \t]*\[[^\]]+\]");

            return from m in regex.Matches(text).OfType<Match>()
                   select m.Value;
        }
Ejemplo n.º 43
0
        static void Main(string[] args)
        {
            TextReader tr = new StreamReader("names.txt");
            string data = tr.ReadToEnd();
            tr.Close();

            // nice and legible - gets quotes and respects backslash escaping
            Regex pattern = new Regex("\"(([^\"\\\\]+|\\\\.)*)\"");
            MatchCollection matches = pattern.Matches(data);
            var names = new List<string>();
            foreach (Match match in matches)
            {
                string value = match.Groups[1].Value;
                names.Add(value);
            }
            names.Sort();
            var values = new List<int>();

            foreach (string name in names)
            {
                IEnumerable<int> nameValues = name.ToUpper().ToCharArray().Select(c => c - 'A' + 1);
                int sum = nameValues.Sum();
                values.Add(sum);
            }

            long total = 0;
            for (int i = 0; i < values.Count(); i++)
            {
                total += (i + 1) * values[i];
            }
            Euler.Utils.OutputAnswer(total.ToString());
        }
 public static string SabotageContent(string someContentOfConfigFile, string originalDbName, string newDbName)
 {
     var result = someContentOfConfigFile;
     var regex = new Regex(@"Catalog\=([^\;]*)\;");
     var matches = regex.Matches(someContentOfConfigFile);
     foreach (Match match in matches)
     {
         if (match.Groups.Count > 1)
         {
             string oldDbName = match.Groups[1].Value;
             if (!originalDbName.Contains("*"))
             {
                 if (originalDbName == oldDbName)
                 {
                     result = result.Replace("Catalog=" + oldDbName + ";", "Catalog=" + newDbName + ";");
                 }
             }
             else
             {
                 if (originalDbName.EndsWith("*"))
                 {
                     if (oldDbName.StartsWith(originalDbName.Substring(0, originalDbName.Length - 1)))
                     {
                         result = result.Replace("Catalog=" + oldDbName + ";", "Catalog=" + newDbName + ";");
                     }
                 }
                 else
                 {
                     throw new NotSupportedException("ConfigFileSaboteur only works with wildcards at the end of the dbname");
                 }
             }
         }
     }
     return result;
 }
Ejemplo n.º 45
0
 public void ShouldRegexMatchTwoLines()
 {
   string content = string.Format("blah:{0}blah", Environment.NewLine);
   Regex regex = new Regex("^.*$", RegexOptions.Multiline);
   regex.IsMatch(content).Should().BeTrue();
   regex.Matches(content).Count.Should().Be(2);
 }
Ejemplo n.º 46
0
        public PluginApi.Plugins.Playlist SearchListRuTr(IPluginContext context, string search)
        {
            //Dim Kino As String = "100,101,1105,1165,1213,1235,124,1245,1246,1247,1248,1250,1386,1387,1388,1389,1390,1391,1478,1543,1576,1577,1642,1666,1670,185,187,1900,1991,208,209,2090,2091,2092,2093,2097,2109,212,2198,2199,22,2200,2201,2220,2221,2258,2339,2343,2365,2459,2491,2540,281,282,312,313,33,352,376,4,404,484,505,511,514,521,539,549,572,599,656,7,709,822,893,905,921,922,923,924,925,926,927,928,93,930,934,941"
            //Dim Dokumentals As String = ",103,1114,113,114,115,1186,1278,1280,1281,1327,1332,137,1453,1467,1468,1469,1475,1481,1482,1484,1485,1495,1569,1959,2076,2107,2110,2112,2123,2159,2160,2163,2164,2166,2168,2169,2176,2177,2178,2323,2380,24,249,251,2537,2538,294,314,373,393,46,500,532,552,56,670,671,672,752,821,827,851,876,882,939,97,979,98"
            //Dim Sport As String = ",1188,126,1287,1319,1323,1326,1343,1470,1491,1527,1551,1608,1610,1613,1614,1615,1616,1617,1620,1621,1623,1630,1667,1668,1675,1697,1952,1986,1987,1997,1998,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2014,2069,2073,2075,2079,2111,2124,2171,2425,2514,255,256,257,259,260,262,263,283,343,486,528,550,626,660,751,845,854,875,978"
            //Dim RequestPost As System.Net.WebRequest = System.Net.WebRequest.Create(TrackerServer & "/forum/tracker.php?f=" & Kino & Dokumentals & Sport & "&nm=" & search)
            System.Net.WebRequest RequestPost = System.Net.WebRequest.Create(TrackerServer + "/forum/tracker.php?nm=" + search);

            if (ProxyEnablerRuTr == true)
            {
                RequestPost.Proxy = new System.Net.WebProxy(ProxyServr, ProxyPort);
            }
            RequestPost.Method      = "POST";
            RequestPost.ContentType = "text/html; charset=windows-1251";
            RequestPost.Headers.Add("Cookie", Cookies);
            RequestPost.ContentType = "application/x-www-form-urlencoded";
            System.IO.Stream myStream = RequestPost.GetRequestStream();
            string           DataStr  = "prev_new=0&prev_oop=0&o=10&s=2&pn=&nm=" + search;

            byte[] DataByte = System.Text.Encoding.GetEncoding(1251).GetBytes(DataStr);
            myStream.Write(DataByte, 0, DataByte.Length);
            myStream.Close();

            System.Net.WebResponse Response   = RequestPost.GetResponse();
            System.IO.Stream       dataStream = Response.GetResponseStream();
            System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream, System.Text.Encoding.GetEncoding(1251));
            string ResponseFromServer         = reader.ReadToEnd();


            System.Collections.Generic.List <Item>         items  = new System.Collections.Generic.List <Item>();
            System.Text.RegularExpressions.Regex           Regex  = new System.Text.RegularExpressions.Regex("(<tr class=\"tCenter hl-tr\">).*?(</tr>)");
            System.Text.RegularExpressions.MatchCollection Result = Regex.Matches(ResponseFromServer.Replace("\n", " "));

            if (Result.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match Match in Result)
                {
                    Item Item = new Item();
                    Regex = new System.Text.RegularExpressions.Regex("(?<=<a data-topic_id=\").*?(?=\")");
                    string LinkID = Regex.Matches(Match.Value)[0].Value;
                    Item.Link        = TrackerServer + "/forum/viewtopic.php?t=" + LinkID + ";PAGEFILMRUTR";
                    Regex            = new System.Text.RegularExpressions.Regex("(?<=" + LinkID + "\">).*?(?=</a>)");
                    Item.Name        = Regex.Matches(Match.Value)[0].Value;
                    Item.ImageLink   = "http://s1.iconbird.com/ico/1012/AmpolaIcons/w256h2561350597291utorrent2.png";
                    Item.Description = GetDescriptionSearhRuTr(Match.Value, Item.Name, LinkID);
                    items.Add(Item);
                }
            }
            else
            {
                Item Item = new Item();
                Item.Name = "Ничего не найдено";
                Item.Link = "";

                items.Add(Item);
            }

            return(PlayListPlugPar(items, context));
        }
Ejemplo n.º 47
0
 private int FindTextOccurrencesInFile(string fileName, string textToSearch)
 {
     string fileContent = System.IO.File.ReadAllText(fileName);
     string cCriteria = @"\b" + textToSearch + @"\b";
     System.Text.RegularExpressions.Regex oRegex = new
         System.Text.RegularExpressions.Regex(cCriteria, RegexOptions.IgnoreCase);
     return oRegex.Matches(fileContent).Count;
 }
Ejemplo n.º 48
0
        //TODO: This would probably be easier to just get a proper JSON parser, I think that is what is used. But for now this is functional, we don't need a lot anyway.
        public static IEnumerable <Tuple <string, string> > ParseStringPairs(string chunkString)
        {
            Regex pairParser = new System.Text.RegularExpressions.Regex(@"^\s*""(?'tag'.*?)""\s*""(?'value'.*?)""[ \t]*$", RegexOptions.Multiline);
            var   matches    = pairParser.Matches(chunkString);

            return(from Match match in matches
                   select new Tuple <string, string>(match.Groups["tag"].Value, match.Groups["value"].Value));
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Replaces the CSS urls.
 /// </summary>
 /// <param name="cssContent">Content of the CSS.</param>
 /// <param name="imagePluginPath">The image plugin path.</param>
 /// <returns>Return content Css with replaced urls.</returns>
 private static String ReplaceCssUrls(String cssContent, String imagePluginPath)
 {
     var regex = new System.Text.RegularExpressions.Regex(UrlRegex);
     var vals = regex.Matches(cssContent).Cast<Match>().ToDictionary(mathe => mathe.Index.ToString(),
                                                               mathe => mathe.Groups[2].Value);
     return regex.Replace(cssContent,
                          match => String.Format(UrlPattern, imagePluginPath, vals[match.Index.ToString()]));
 }
Ejemplo n.º 50
0
        public List <string> ParseVariables(string code)
        {
            var result = new List <string> ();

            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups[1].Value;
                if (name == "end" || name == "selected" || string.IsNullOrEmpty(name) || name.Trim().Length == 0)
                {
                    continue;
                }
                if (!result.Contains(name))
                {
                    result.Add(name);
                }
            }
            return(result);
        }
Ejemplo n.º 51
0
        private string GetRegexPattern(string abbr)
        {
            string numbers   = "[0-9]+";
            var    regex     = new System.Text.RegularExpressions.Regex(numbers);
            var    matches   = regex.Matches(abbr);
            var    evaluator = new System.Text.RegularExpressions.MatchEvaluator(EntryNumber);

            return("^" + regex.Replace(abbr, evaluator) + "$");
        }
Ejemplo n.º 52
0
        public string FormatDescriptionFileRuTr(string HTML)
        {
            HTML = HTML.Replace("\n", "");

            string Title = null;

            try
            {
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("(?<=<title>).*?(</title>)");
                Title = Regex.Matches(HTML)[0].Value;
            }
            catch (Exception ex)
            {
                Title = ex.Message;
            }


            string SidsPirs = null;

            try
            {
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("(<td class=\"borderless bCenter pad_8\">).*?(?=</div>)");
                SidsPirs = "<p>" + Regex.Matches(HTML)[0].Value;
            }
            catch (Exception ex)
            {
                SidsPirs = ex.Message;
            }


            string ImagePath = null;

            try
            {
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("(?<=<var class=\"postImg postImgAligned img-right\" title=\").*?(?=\">)");
                ImagePath = Regex.Matches(HTML)[0].Value;
            }
            catch (Exception ex)
            {
            }


            string InfoFile = null;

            try
            {
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("(<span class=\"post-b\">).*(?=<div class=\"sp-wrap\">)");
                InfoFile = Regex.Matches(HTML)[0].Value;
            }
            catch (Exception ex)
            {
                InfoFile = ex.Message;
            }

            return("<html><captionn align=\"left\" valign=\"top\"><strong>" + Title + "</strong></caption><style>.leftimg {float:left;margin: 7px 7px 7px 0;</style>" + SidsPirs + "<table><tbody><tr><th align=\"left\" width=\"220\" valign=\"top\"><img src=\"" + ImagePath + "\"width=\"220\" height=\"290\" class=\"leftimg\" <font face=\"Arial Narrow\" size=\"3\">" + InfoFile + "</tr></tbody></table><div></font></div></html>");
        }
Ejemplo n.º 53
0
        public int compareVersion(string Version1, string Version2)
        {
            System.Text.RegularExpressions.Regex           regex = new System.Text.RegularExpressions.Regex(@"([\d]+)");
            System.Text.RegularExpressions.MatchCollection m1    = regex.Matches(Version1);
            System.Text.RegularExpressions.MatchCollection m2    = regex.Matches(Version2);
            int min = Math.Min(m1.Count, m2.Count);

            for (int i = 0; i < min; i++)
            {
                if (Convert.ToInt32(m1[i].Value) > Convert.ToInt32(m2[i].Value))
                {
                    return(1);
                }
                if (Convert.ToInt32(m1[i].Value) < Convert.ToInt32(m2[i].Value))
                {
                    return(-1);
                }
            }
            return(0);
        }
Ejemplo n.º 54
0
 private bool IsValidSubdirectory(string path)
 {
     if (_regex.Matches(path).Count <= 2)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 55
0
        /// <summary>
        /// 获取图片URL地址
        /// </summary>
        private string GetImgUrl(string imgTagStr)
        {
            string str = "";

            System.Text.RegularExpressions.Regex regObj = new System.Text.RegularExpressions.Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match matchItem in regObj.Matches(imgTagStr))
            {
                str = matchItem.Value;
            }
            return(str);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// HTMLファイルからアンカータグ部分をリンクを抜き出します。
        /// </summary>
        /// <param name="HTML"></param>
        /// <returns></returns>
        public static ICollection <string> GetLinkHtml(string HTML)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<A[^>]*?HREF\s*=(\s*|\s*[""])([^"">]+)([""][^>]*?|[^>]*?)>([\s\S]*?)<\/A>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            List <string> list = new List <string>();

            foreach (System.Text.RegularExpressions.Match match in regex.Matches(HTML))
            {
                list.Add(match.Value);
            }
            return(list);
        }
Ejemplo n.º 57
0
        private void btnParse_Click(object sender, RoutedEventArgs e)
        {
            MatchCollection matchedEmails = regex.Matches(txtParse.Text);
            string          matches       = "";

            for (int count = 0; count < matchedEmails.Count; count++)
            {
                matches += matchedEmails[count].Value + Environment.NewLine;
            }

            MessageBox.Show(matches);
        }
            private static bool CheckDomainName(string subjectName, string targetHost)
            {
                string pattern = string.Empty;

                System.Text.RegularExpressions.Regex           regex           = new System.Text.RegularExpressions.Regex("CN\\s*=\\s*([^,]*)");
                System.Text.RegularExpressions.MatchCollection matchCollection = regex.Matches(subjectName);
                if (matchCollection.Count == 1 && matchCollection[0].Success)
                {
                    pattern = matchCollection[0].Groups[1].Value.ToString();
                }
                return(ServicePointManager.ChainValidationHelper.Match(targetHost, pattern));
            }
        private string GetWorkspace(string cmdLine)
        {
            var rex = new System.Text.RegularExpressions.Regex("-s\\s\"(?<path>.*)\"");
            var m   = rex.Matches(cmdLine);

            if (m.Count == 0)
            {
                throw new ArgumentException();
            }

            return(m[0].Groups["path"].Captures[0].Value);
        }
Ejemplo n.º 60
0
        public List <string> ExtractList(IDocument document, string regex)
        {
            var list = new List <string>();
            var regularExpression = new System.Text.RegularExpressions.Regex(regex);
            var matches           = regularExpression.Matches(document.DocumentElement.OuterHtml);

            foreach (Match match in matches)
            {
                list.Add(match.Value);
            }
            return(list);
        }