Inheritance: IEnumerable
 internal RegExpMatch(ArrayPrototype parent, Regex regex, Match match, string input) : base(parent, typeof(RegExpMatch))
 {
     this.hydrated = false;
     this.regex = regex;
     this.matches = null;
     this.match = match;
     base.SetMemberValue("input", input);
     base.SetMemberValue("index", match.Index);
     base.SetMemberValue("lastIndex", (match.Length == 0) ? (match.Index + 1) : (match.Index + match.Length));
     string[] groupNames = regex.GetGroupNames();
     int num = 0;
     for (int i = 1; i < groupNames.Length; i++)
     {
         string name = groupNames[i];
         int num3 = regex.GroupNumberFromName(name);
         if (name.Equals(num3.ToString(CultureInfo.InvariantCulture)))
         {
             if (num3 > num)
             {
                 num = num3;
             }
         }
         else
         {
             Group group = match.Groups[name];
             base.SetMemberValue(name, group.Success ? group.ToString() : null);
         }
     }
     this.length = num + 1;
 }
Exemple #2
1
 public int RowCount(string source)
 {
   Regex rowRegex = new Regex(_rowDelimiter);
   _source = source;
   _rows = rowRegex.Matches(_source);
   return _rows.Count;
 }
Exemple #3
0
 public override void Matched(MatchCollection matches, uint posterID, uint victimID, DateTime now, MySqlConnection con, SingleNewscanRequestHandler handler, ParserResponse resp)
 {
     Dictionary<uint, String> uidToIgmNameCache = new Dictionary<uint, string>();
     foreach(Match outerMatch in matches) {
         String empfaenger;
         if(!uidToIgmNameCache.TryGetValue(victimID, out empfaenger)) {
             MySqlCommand igmNameQry = new MySqlCommand("SELECT igmname FROM " + DBPrefix + "igm_data WHERE id=?igmid", con);
             igmNameQry.Parameters.Add("?igmid", MySqlDbType.UInt32).Value = victimID;
             Object obj = igmNameQry.ExecuteScalar();
             empfaenger = (String)obj;
             uidToIgmNameCache.Add(victimID, empfaenger);
         }
         Transport t = new Transport(
             uint.Parse(outerMatch.Groups[1].Value),
             uint.Parse(outerMatch.Groups[2].Value),
             uint.Parse(outerMatch.Groups[3].Value),
             empfaenger,
             outerMatch.Groups[5].Value,
             IWDBUtils.parsePreciseIWTime(outerMatch.Groups[4].Value)
         );
         MatchCollection c = Regex.Matches(outerMatch.Groups[7].Value, @"\s(" + RessourcenName + @")\s+(" + Number + ")");
         foreach(Match m in c) {
             t.SetRess(m.Groups[1].Value, int.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.Any));
         }
         t.ToDB(con, DBPrefix, handler.BesData, resp, "Übergabebericht");
     }
 }
		private void getVulnerablePages(MatchCollection mirrors) {
			foreach (var pageUrl in mirrors) {
				string data = tryGetUrlData(BASE_URL + pageUrl);
				extractUrl(data);
				extractAndSaveHtmlPage(data);
			}
		}
 private List<Link> getLinkList(MatchCollection matches)
 {
     List<Link> links = new List<Link>();
     for (int i = 0; i < matches.Count; i++)
         addLink(i, matches, links);
     return links;
 }
 private static IHtmlCollection CreateCollection(MatchCollection matches)
 {
     var elements = new List<IHtmlElement>();
     foreach (Match match in matches)
         elements.Add(CreateElement(match));
     return new HtmlCollection(elements);
 }
Exemple #7
0
        /// <summary>
        ///  指定文字列を読込んで、対応する時間を取得する
        /// </summary>
        /// <param name="mc">正規で検索した文字列</param>
        /// <param name="fileContent">ファイル内容</param>
        private void GetTimeForContent(System.Text.RegularExpressions.MatchCollection mc, string fileContent)
        {
            _logger.Debug("***GetTimeForContent START***");

            string strRtn     = string.Empty;
            string strContent = string.Empty;

            // 指定検索内容情報初期化
            SearchContentInfo selContentInfo = null;

            string strDateTime = string.Empty;

            foreach (System.Text.RegularExpressions.Match m in mc)
            {
                // 指定キーによって対応内容をリストへ格納する
                selContentInfo = new SearchContentInfo();

                selContentInfo.selConStartIndex  = m.Index;
                selContentInfo.selTimeStartIndex = fileContent.IndexOf("DateTime", m.Index + REGEX.Length + 1);
                strDateTime = fileContent.Substring(selContentInfo.selTimeStartIndex + 9, 34);
                selContentInfo.selConForTime = DateTime.Parse(strDateTime);

                lstSelContentInfo.Add(selContentInfo);
            }

            _logger.Debug("***GetTimeForContent END***");
        }
        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);
        }
        public void StartScan()
        {

            var isCountOkay=false;
  
            while (!_shouldStop)
            {                    
                    _matches = _m.PidToInstances(_pid, _pattern);
                    try
                    {
                        if (_matches.Count > 0)
                            isCountOkay = true;
                        else
                            isCountOkay = false;
                    }
                    catch
                    {
                        _m.ResultsStatus = 2;
                    }
                    


                    if(_m.ResultsStatus==1 && isCountOkay)
                    {
                        foreach (Match match in _matches)
                        {
                            if (Info.Contains(match.Value) == false)
                                Info.Add(match.Value);
                        }
                    }             
            }

        }
Exemple #10
0
    private string YoutubeURL(string Value)
    {
        string checkstr = Value;
        string PostBody = checkstr;

        if (PostBody.Contains("youtube"))
        {
            String pattern1 = @"(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)";
            System.Text.RegularExpressions.Regex           regex1   = new System.Text.RegularExpressions.Regex(pattern1);
            System.Text.RegularExpressions.MatchCollection matches1 = regex1.Matches(PostBody);
            for (int j = 0; j < matches1.Count; j++)
            {
                //string temp = SetVideoForPlay(test);
                string youtubeUrl = PostBody;
                string vCode      = youtubeUrl.Substring(youtubeUrl.LastIndexOf("v=") + 2);
                if (vCode.Contains("&"))
                {
                    vCode = vCode.Substring(0, vCode.LastIndexOf("&"));
                }
                string sHtml = @"http://www.youtube.com/v/{0}&autoplay=0";
                string tenp  = String.Format(sHtml, vCode);
                PostBody = PostBody.Replace(matches1[j].Value, String.Format("<br /><iframe width='480' height='390' src=\"{0}\"></iframe><br />", tenp));
            }
            checkstr = PostBody;
        }
        return(PostBody);
    }
Exemple #11
0
        public static List <double> GetNumberFromString(string str)
        {
            str = str.Replace("/", "per");
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(str, @".*?([-]{0,1} *(\d+.\d+)|\d+)");

            List <double> nums = new List <double>();

            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                string value = match.Groups[1].Value;

                value = value.Replace(" ", "");

                double num1 = -1;
                double.TryParse(value, out num1);
                if (num1 == 0)
                {
                    System.Globalization.NumberStyles style   = System.Globalization.NumberStyles.Number | System.Globalization.NumberStyles.AllowCurrencySymbol;
                    System.Globalization.CultureInfo  culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
                    double.TryParse(value, style, culture, out num1);
                }
                nums.Add(num1);
            }
            return(nums);
        }
        public string RecursiveFindDynamicClause(MatchCollection matchs, SqlCommand sqlCommand)
        {
            string result = string.Empty;
            if (matchs.Count < 1)
                return result;

            foreach (Match match in matchs)
            {
                result = match.Value;
                string reResult = RecursiveFindDynamicClause(RegexPattern.DynamicClausePattern.Matches(match.Groups["DynamicClause"].Value), sqlCommand);
                if (!sqlCommand.Parameters.Exists((c) =>
                {
                    bool r = false;
                    string tempResult = string.IsNullOrEmpty(reResult) ? result : result.Replace(reResult, "");
                    if (SqlUtil.ContainsParameterName(tempResult, c.ParameterName))
                    {
                        //当值不为“null”、“DBNull”和“空白字符串”时参数值才算是有效
                        if (c.Value != null && c.Value != DBNull.Value && c.Value.ToString().Trim() != string.Empty)
                        {
                            r = true;
                        }

                        if (result.StartsWith(LEFT_BRACE_DUBLE_QUESTION_MARK))
                        {
                            r = true;
                        }
                    }
                    return r;
                }))
                {
                    removeClauseStack.Push(result);
                }
            }
            return result;
        }
        private static string[] FindLongestConsecutivePair(MatchCollection usernames)
        {
            int bestLength = 0,
                fromIndex = 0;

            if (usernames.Count == 1)
            {
                Console.WriteLine(usernames[0].Value);

                return new string[]
                {
                    usernames[0].Value
                };
            }

            for (int i = 1; i < usernames.Count; i++)
            {
                string current = usernames[i].Value,
                    prev = usernames[i - 1].Value;

                int currentLength = current.Length + prev.Length;

                if (currentLength > bestLength)
                {
                    bestLength = currentLength;
                    fromIndex = i - 1;
                }
            }

            return new string[]
            {
                usernames[fromIndex].Value,
                usernames[fromIndex + 1].Value
            };
        }
Exemple #14
0
        public void parseText()
        {
            MessengerParser parser = new MessengerParser();
            string pattern;

            if (skypeRadio.Checked)
            {
                pattern = MessengerParser.SKYPE_PATTERN;
            }
            else if (qip9095Radio.Checked)
            {
                pattern = MessengerParser.QIP9095_PATTERN;
            }
            else
            {
                pattern = "";
            }

            chatMatches = parser.parseText(inputText.Text, pattern);
            totalData.Clear();

            GroupCollection groups;

            foreach (Match match in chatMatches)
            {
                groups = match.Groups;

                if (!totalData.ContainsKey(groups[3].Value))
                {
                    totalData.Add(groups[3].Value, 0);
                }
                totalData[groups[3].Value]++;
            }
        }
        public int BatchInsertIncidentCollections(MatchCollection collections, ConfigInitializer.IncidentTableEntity incidentTable, out HashSet<string> duplicateHash, bool SKIP)
        {
            duplicateHash = new HashSet<string>();
            if (SKIP) return 0;

            var queryText = incidentTable.ToString();
            var incident = new DataNormalizer.DataEntity.Incident(incidentTable);
            int successCount = 0;
            //var queryText = $"INSERT into {this.tableInfo.tableName} {this.tableInfo.queryItemPattern} VALUES {this.tableInfo.queryValuePattern}";
            using (var transaction = this._connection.BeginTransaction())
            {
                foreach (Match match in collections)
                {
                    var cmd = new SqlCommand(queryText, this._connection, transaction);
                    incident.registerSqlCommand(match, ref cmd);
                    try
                    {
                        cmd.ExecuteNonQuery();
                        Console.WriteLine($"Insert: {match.Groups[1].Value}");
                        successCount += 1;
                    }
                    catch
                    {
                        var incidentString = match.Groups[1].Value;
                        duplicateHash.Add(incidentString);
                        Console.WriteLine($"Duplicate Incident: {incidentString}");
                    }
                }
                transaction.Commit();
            }
            return successCount;
        }
Exemple #16
0
        /// <summary>
        /// Unicode16转汉字
        /// </summary>
        /// <param name="countText"></param>
        /// <returns></returns>
        public static string Unicode16ToGB(string countText)
        {
            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(countText, "&#x(\\w{1,4});");
            if (mc != null && mc.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match m2 in mc)
                {
                    string v = m2.Value;
                    string a = m2.Groups[1].Value;

                    var b = int.Parse(a, System.Globalization.NumberStyles.HexNumber);

                    try
                    {
                        char word = (char)b;
                        countText = countText.Replace(v, word.ToString());
                    }
                    catch (Exception ex)
                    {
                        return(countText); //throw ;
                    }
                }
            }
            return(countText);
        }
Exemple #17
0
        /// <summary>
        /// Extracts the matches of this pattern from <paramref name="source" />.
        /// </summary>
        /// <param name="fileName">The name of the file associated with <paramref name="source" />.</param>
        /// <param name="source">The source string</param>
        /// <returns>
        /// A collection of found matches.
        /// </returns>
        public MatchCollection Extract(string fileName, string source)
        {
            MatchCollection resultMatches = new MatchCollection();
            LineCounter lineCounter = new LineCounter(source);

            RegexMatch regexMatch = scanner.Match(source);
            while (regexMatch.Success)
            {
                Match match = new Match();
                match["Path"] = Path.GetDirectoryName(fileName);
                match["File"] = Path.GetFileName(fileName);
                match["LineNumber"] = lineCounter.CountTo(regexMatch.Index).InvariantToString();
                foreach (string groupName in scanner.GetGroupNames())
                {
                    // ignore default-names like '0', '1' ... as produced
                    // by the Regex class
                    if (Char.IsLetter(groupName[0]) || (groupName[0] == '_'))
                    {
                        match[groupName] = ConcatenateCaptures(regexMatch.Groups[groupName]);
                    }
                }
                resultMatches.Add(match);
                regexMatch = regexMatch.NextMatch();
            }
            return resultMatches;
        }
Exemple #18
0
        private string BuildHGNXFromBGAGameLog(string gameLog)
        {
            string hgnx = "";

            InitPieces();
            string _pattern = "\"x\":\"(-?\\d*)\",\"y\":\"(-?\\d*)\",\"h\":\\d*,\"id\":\"(\\d*)\"";
            _mc = Regex.Matches(gameLog, _pattern, RegexOptions.IgnoreCase);

            string moves = "";
            for (int i = 0; i < _mc.Count; i++)
            {
                int index = GetPieceIndex(_mc[i].Groups[3].Value);
                if ((i % 2 == 0 && Int32.Parse(_mc[i].Groups[3].Value) >= 12) ||
                    (i % 2 == 1 && Int32.Parse(_mc[i].Groups[3].Value) < 12))
                {
                    moves += "-1,-999,-999,-999,-999,0, " + "\n";
                }
                if (index != -1)
                {
                    moves += index + "," + BuildMove(index, Int32.Parse(_mc[i].Groups[1].Value), Int32.Parse(_mc[i].Groups[2].Value)) + "\n";
                }
            }

            GetGameInfo(gameLog);
            hgnx = _id + "\n" + _type + "\n" + _wp + "\n" + _bp + "\n" + _result + "\n" + _wt + "\n" + _bt + "\n" + "-1\n-1\n-1\n-1\n0\n" + moves.Substring(0, moves.Length - 1);
            return hgnx;
        }
Exemple #19
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);
        }
Exemple #20
0
        /// <summary>
        /// TODO: Update with balanced group constructs
        /// </summary>
        /// <param name="body"></param>
        /// <param name="tagName"></param>
        /// <param name="stripEnclosingTags"></param>
        /// <returns></returns>
        public static String[] GetHtmlTagBodies(String body, String tagName, bool stripEnclosingTags)
        {
            System.Text.RegularExpressions.MatchCollection mc = null;
            String[] bodies = null;
            String   tmp    = null;
            int      x      = 0;

            // Match opening->closing tag, nested tags not handled
            mc = Regex.Matches(body, @"<\s*?" + tagName + @"((\s*?)|(\s+?\w.*?))>.*?<\s*?\/\s*?" + tagName + @"\s*?>", RegexOptions.Singleline);

            if (mc != null && mc.Count > 0)
            {
                bodies = new String[mc.Count];

                foreach (Match m in mc)
                {
                    tmp = m.ToString();

                    if (stripEnclosingTags)
                    {
                        tmp = Regex.Replace(tmp, @"<\s*?" + tagName + @"((\s*?)|(\s+?\w.*?))>", "");
                        tmp = Regex.Replace(tmp, @"<\s*?\/\s*?" + tagName + @"\s*?>", "");
                    }

                    bodies[x++] = tmp;
                }
            }

            return(bodies);
        }
Exemple #21
0
        static public axis fromJson(string json)
        {
            if (jsonParser == null)
            {
                jsonParser = new Regex("\"input\": \"(.*)\",.*" +
                                       "\"key\": \"(.*)\",.*" +
                                       "\"type\": \"(.*)\",.*" +
                                       "\"isKey\": \"(.*)\",.*" +
                                       "\"name\": \"(.*)\",.*" +
                                       "\"rest\": \"(.*)\"");
            }
            MatchCollection matches = jsonParser.Matches(json);
            GroupCollection groups  = matches[0].Groups;

            string   input  = groups[1].Value;
            int      ikey   = Int32.Parse(groups[2].Value);
            KeyCode  key    = (KeyCode)ikey;
            int      itype  = Int32.Parse(groups[3].Value);
            axisType type   = (axisType)itype;
            int      iIsKey = Int32.Parse(groups[4].Value);
            bool     isKey  = (iIsKey != 0);
            string   name   = groups[5].Value;
            float    rest   = float.Parse(groups[6].Value, CultureInfo.InvariantCulture);

            axis a = new axis();

            a.input = input;
            a.key   = key;
            a.type  = type;
            a.isKey = isKey;
            a.name  = name;
            a.rest  = rest;
            return(a);
        }
Exemple #22
0
 public static string usc2转ansi(string str)
 {
     if (str == "" || str == null)
     {
         return("");
     }
     else
     {
         System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(str, "\\\\u([\\w]{4})");
         if (mc != null && mc.Count > 0)
         {
             foreach (System.Text.RegularExpressions.Match m2 in mc)
             {
                 string v     = m2.Value;
                 string word  = v.Substring(2);
                 byte[] codes = new byte[2];
                 int    code  = Convert.ToInt32(word.Substring(0, 2), 16);
                 int    code2 = Convert.ToInt32(word.Substring(2), 16);
                 codes[0] = (byte)code2;
                 codes[1] = (byte)code;
                 str      = str.Replace(v, System.Text.Encoding.Unicode.GetString(codes));
             }
         }
         return(str);
     }
 }
        /// <summary>
        /// This method builds the award cache with the given data from the medal data file.
        /// This method WILL CLEAR the award cache from any existing medals
        /// </summary>
        /// <param name="MedalsMatches"></param>
        /// <param name="RanksMatches"></param>
        public static void BuildAwardCache(MatchCollection MedalsMatches, MatchCollection RanksMatches)
        {
            // Clear out the award cache!
            AwardCache.Clear();

            // Convert each medal match into an object, and add it to the award cache
            foreach (Match ArrayMatch in MedalsMatches)
            {
                AwardCache.AddAward(
                    new Award(
                        ArrayMatch.Groups["MedalIntId"].Value,
                        ArrayMatch.Groups["MedalStrId"].Value,
                        ArrayMatch.Groups["RewardType"].Value,
                        ParseCondition(ArrayMatch.Groups["Conditions"].Value)
                    )
                );
            }

            // Convert ranks into objects, and also add them to the award cache
            foreach (Match ArrayMatch in RanksMatches)
            {
                AwardCache.AddRank(
                    new Rank(
                        Int32.Parse(ArrayMatch.Groups["RankId"].Value),
                        ParseCondition(ArrayMatch.Groups["Conditions"].Value)
                    )
                );
            }
        }
        ///// <summary>
        ///// 验证域名格式
        ///// </summary>
        ///// <param name="domain">域名</param>
        ///// <returns>验证结果</returns>
        //public static bool IsDomain(this string domain)
        //{
        //    int len = domain.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;
        //    return len == 2;
        //}
        ///// <summary>
        ///// 验证是否域名格式-可不带后缀
        ///// </summary>
        ///// <param name="domainName">域名</param>
        ///// <returns></returns>
        //public static bool IsDomain(this string domainName)
        //{
        //    bool ret = false;
        //    if (domainName.Contains("xn--"))
        //    {
        //        return ret;
        //    }
        //    Regex r = new Regex(@"[\u4e00-\u9fa5]+");
        //    Match mc = r.Match(domainName);
        //    if (mc.Length != 0)//含中文域名
        //    {
        //        IdnMapping dd = new IdnMapping();
        //        domainName = dd.GetAscii(domainName);
        //    }
        //    if (domainName.Substring(0, 1) == "-")
        //    {
        //        return ret;
        //    }
        //    if (domainName.Contains("-."))
        //    {
        //        return ret;
        //    }
        //    if (!domainName.Contains("."))
        //    {
        //        domainName += ".com";
        //    }
        //    //英文域名格式
        //    System.Text.RegularExpressions.MatchCollection mc2 = System.Text.RegularExpressions.Regex.Matches(domainName, @"^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$");
        //    if (mc2 != null && mc2.Count > 0)
        //    {
        //        return true;
        //    }
        //    return ret;
        //}
        /// <summary>
        /// 验证是否域名格式-带后缀
        /// </summary>
        /// <param name="domainName">域名</param>
        /// <returns></returns>
        public static bool IsDomain(this string domainName)
        {
            bool ret = false;

            if (!domainName.Contains("."))
            {
                return(ret);
            }

            Regex r  = new Regex(@"[\u4e00-\u9fa5]+");
            Match mc = r.Match(domainName);

            if (mc.Length != 0)//含中文域名
            {
                IdnMapping dd = new IdnMapping();
                domainName = dd.GetAscii(domainName);
            }
            //英文域名格式
            System.Text.RegularExpressions.MatchCollection mc2 = System.Text.RegularExpressions.Regex.Matches(domainName, @"^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$");
            if (mc2 != null && mc2.Count > 0)
            {
                return(true);
            }
            return(ret);
        }
Exemple #25
0
        /// <summary>
        /// 获取字符串中的指定内容集合
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <param name="">正则表达式</param>
        /// <returns></returns>
        public static List <string> RegexsSplit(string input, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
        {
            List <string> result = new List <string>();

            if (string.IsNullOrEmpty(pattern) || string.IsNullOrEmpty(input))
            {
                return(result);
            }
            bool isMatch = System.Text.RegularExpressions.Regex.IsMatch(input, pattern);

            if (!isMatch)
            {
                return(result);
            }
            System.Text.RegularExpressions.MatchCollection matchCol = System.Text.RegularExpressions.Regex.Matches(input, pattern);

            if (matchCol.Count > 0)
            {
                for (int i = 0; i < matchCol.Count; i++)
                {
                    result.Add(matchCol[i].Value);
                }
            }
            return(result);
        }
Exemple #26
0
 private void ParseMeters(MatchCollection matches)
 {
     string metersString = matches[1].Groups[0].Value.Trim();
     string[] arrayMeters = metersString.Split(new char[] { ' ' });
     string meterValue = arrayMeters[0];
     meters = double.Parse(meterValue);
 }
        public void AutoGenerateChildren(MatchCollection matches)
        {
            int count = 0;
            foreach (Match match in matches)
            {
                m_mon.SetProgress((double) count, (double) matches.Count, Catalog.GetString("Processing Children..."), false);
                DegreeMinutes[] coord =  Utilities.ParseCoordString(match.Captures[0].Value);
                System.Console.WriteLine(Utilities.getCoordString(coord[0], coord[1]));

                Waypoint newPoint = new Waypoint ();
                Geocache parent = m_mon.SelectedCache;
                newPoint.Symbol = "Reference Point";
                newPoint.Parent = parent.Name;
                newPoint.Lat = coord[0].GetDecimalDegrees();
                newPoint.Lon = coord[1].GetDecimalDegrees();
                newPoint.Desc = Catalog.GetString("Grabbed Waypoint");
                String name = "RP" + parent.Name.Substring (2);
                if (m_mon.Configuration.IgnoreWaypointPrefixes)
                {
                    name = parent.Name;
                }
                name = Engine.getInstance().Store.GenerateNewName(name);
                newPoint.Name = name;
                CacheStore store = Engine.getInstance ().Store;
                store.AddWaypointAtomic (newPoint);
                count++;
            }
        }
        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);
        }
Exemple #29
0
        private static string GetReplace(string content, string splitKey1, string splitKey2, string newChars)
        {
            //splitKey1 第一个正则式匹配

            //splitKey2 匹配结果中再次匹配进行替换

            if (splitKey1 != null && splitKey1 != "" && splitKey2 != null && splitKey2 != "")
            {
                Regex rg = new Regex(splitKey1, RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.MatchCollection mc = rg.Matches(content);


                foreach (System.Text.RegularExpressions.Match mc1 in mc)
                {
                    string oldChar = mc1.ToString();
                    string newChar = new Regex(splitKey2, RegexOptions.IgnoreCase).Replace(oldChar, newChars);
                    content = content.Replace(oldChar, newChar);
                }
                return(content);
            }
            else
            {
                if (splitKey2 != null && splitKey2 != "")
                {
                    Regex rg = new Regex(splitKey2, RegexOptions.IgnoreCase);
                    return(rg.Replace(content, newChars));
                }
            }
            return(content);
        }
        private List<WikiLink> BuildLinkList(PreProcessorContext context, MatchCollection regExLinks)
        {
            var wikiLinks = (from Match match in regExLinks
                             select new WikiLink
                                        {
                                            PagePath = CreatePath(context.Page.PagePath, match.Groups[1].Value),
                                            Title = match.Groups[3].Value
                                        }).ToList();

            var treeNodes = _repository.Find(wikiLinks.Select(x => x.PagePath).ToList());
            foreach (var link in wikiLinks)
            {
                var node = treeNodes.FirstOrDefault(x => x.Path.Equals(link.PagePath));
                if (node != null)
                {
                    if (string.IsNullOrEmpty(link.Title))
                        link.Title = node.Page.Title;
                }

                link.Exists = node != null;
            }

            foreach (var link in wikiLinks)
            {
                if (string.IsNullOrEmpty(link.Title))
                    link.Title = link.PagePath.Name;
            }

            return wikiLinks;
        }
        public void AutoGenerateChildren(MatchCollection matches)
        {
            int count = 0;
            m_App.CacheStore.StartUpdate();
            foreach (Match match in matches)
            {
                DegreeMinutes[] coord = Utilities.ParseCoordString (match.Captures[0].Value);
                System.Console.WriteLine (Utilities.getCoordString (coord[0], coord[1]));

                Waypoint newPoint = new Waypoint ();
                Geocache parent = m_Cache;
                newPoint.Symbol = "Reference Point";
                newPoint.Parent = parent.Name;
                newPoint.Lat = coord[0].GetDecimalDegrees ();
                newPoint.Lon = coord[1].GetDecimalDegrees ();
                newPoint.Desc = Catalog.GetString ("Grabbed Waypoint");
                String name = "RP" + parent.Name.Substring (2);
                if (m_App.AppConfig.IgnoreWaypointPrefixes)
                {
                    name = parent.Name;
                }
                name = m_App.CacheStore.GetUniqueName(name);
                newPoint.Name = name;
                m_App.CacheStore.AddWaypointOrCache(newPoint, false, false);
                count++;
            }
            m_App.CacheStore.CompleteUpdate();
            m_App.RefreshAll();
        }
Exemple #32
0
 public static string regexFun(string target, string expr, object g, regexAct ra, string replStr, int replCnt, int replStart, ref MatchCollection o, int capID) {
     int gn = g is int ? Int32.Parse(g.ToString()) : 0;
     if (capID < 0) { capID = 0; }
     Regex regex = new Regex(expr, RegexOptions.Multiline | RegexOptions.IgnoreCase);
     try {
         switch (ra) {
             case regexAct.Match:
                 var varMatch = regex.Match(target);
                 if (!varMatch.Success) {
                     return null;
                 } else if (g is String && Array.Exists(regex.GetGroupNames(), gpnm => (gpnm == g.ToString()))) {
                     return varMatch.Groups[g.ToString()].Captures[capID].Value;
                 } else if (g is int || Int32.TryParse(g.ToString(), out gn)) {
                     return varMatch.Groups[gn].Captures[capID].Value;
                 } else {
                     return varMatch.Groups[0].Captures[capID].Value;
                 }
             case regexAct.Replace:
                 return regex.Replace(target, (string)replStr, replCnt, replStart);
             case regexAct.Matches:
                 var ms = regex.Matches(target);
                 o = ms;
                 return "0";
             default:
                 return "err:-1";
         }
     } catch{
         return "err:-2";
     }
 }
Exemple #33
0
        public void ChangeResultDic(Dictionary <string, string> dic)
        {
            if (!dic.ContainsKey("电话号码"))
            {
                return;
            }
            List <string> css = getCss();
            string        num = dic["电话号码"];

            string result = "";

            System.Text.RegularExpressions.MatchCollection mc = Regex.Matches(num, "<span class='([^<]*?)'>([^<]*?)</span>");
            if (mc.Count > 0)
            {
                foreach (Match item in mc)
                {
                    string c = item.Result("$1");
                    if (css.Contains(c))
                    {
                        result += item.Result("$2");
                    }
                }
            }
            else
            {
                return;
            }
            dic["电话号码"] = result;
        }
Exemple #34
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);
        }
Exemple #35
0
        public override void Matched(MatchCollection matches, uint posterID, uint victimID, DateTime now, MySqlConnection con, SingleNewscanRequestHandler handler, ParserResponse resp)
        {
            foreach (Match m in matches) {

                MySqlCommand cleanup = new MySqlCommand(@"DELETE FROM techtree_useritems
            USING (" + DBPrefix + @"techtree_useritems AS techtree_useritems) INNER JOIN (" + DBPrefix + @"techtree_items AS techtree_items) ON techtree_items.ID=techtree_useritems.itemid
            WHERE techtree_useritems.uid=?uid AND techtree_items.type = 'for'", con);
                cleanup.Parameters.Add("?uid", MySqlDbType.UInt32).Value = victimID;
                cleanup.Prepare();
                cleanup.ExecuteNonQuery();

                String[] parts = m.Groups[1].Value.Split('\n');
                MySqlCommand idQry = new MySqlCommand(@"SELECT ID FROM " + DBPrefix + @"techtree_items WHERE Name=?name", con);
                idQry.Parameters.Add("?name", MySqlDbType.String);
                idQry.Prepare();

                MySqlCommand idInsert = new MySqlCommand(@"INSERT IGNORE INTO " + DBPrefix + @"techtree_useritems (uid, itemid, count) VALUES (?uid, ?itemid, 1)", con);
                idInsert.Parameters.Add("?uid", MySqlDbType.UInt32).Value = victimID;
                idInsert.Parameters.Add("?itemid", MySqlDbType.UInt32);
                idInsert.Prepare();

                foreach (String forschung in parts) {
                    idQry.Parameters["?name"].Value = forschung;
                    object res = idQry.ExecuteScalar();
                    if (res == null)
                        continue;
                    uint id = (uint)res;
                    idInsert.Parameters["?itemid"].Value = id;
                    idInsert.ExecuteNonQuery();
                }
            }
            resp.Respond("Forschungsübersicht eingelesen!");
        }
 public static void GrabberIp()
 {
     while (true)
     {
         Thread.Sleep(1000*20);
         using (_client = new WebClient())
         {
             var db = new DataProviderProxy();
             _client.Encoding = Encoding.UTF8;
             Dictionary<int, string> dbResault = db.GetSiteWithId();
             if (dbResault == null) continue;
             try
             {
                 string resault = _client.DownloadString(@"http://" + dbResault.Values.ElementAt(0));
                 _regex = new Regex(_patternIp);
                 _matchCol = _regex.Matches(resault);
                 foreach (Match match in _matchCol)
                 {
                     Console.WriteLine("найден ip: " + match.Groups[1].Value);
                     db.InsertIp(dbResault.Keys.ElementAt(0), match.Groups[1].Value);
                 }
             }
             catch
             {
                 Console.WriteLine("errorConnect 404");
             }
             finally
             {
                 db.UpdateDate(dbResault.Keys.ElementAt(0), DateTime.Now);
             }
         }
     }
 }
Exemple #37
0
        private static Collection<LinkItem> cleanLinks(MatchCollection m1)
        {
            Collection<LinkItem> list = new Collection<LinkItem>();

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    LinkItem i = new LinkItem();
                    i.Href = m2.Groups[1].Value;

                    // 4.
                    // Remove inner tags from text and add.
                    string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                    RegexOptions.Singleline);
                    i.Text = t;

                    list.Add(i);
                }
            }
            return list;
        }
Exemple #38
0
        private static Collection<LinkItem> cleanLinks2(MatchCollection m1)
        {
            Collection<LinkItem> list = new Collection<LinkItem>();

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();
                int pos = value.IndexOf(' ');
                if (pos == -1)
                {
                    pos = value.IndexOf('\n');
                }
                if (pos == -1)
                {
                    pos = value.IndexOf('\t');
                }
                if (pos != -1)
                {
                    value = value.Substring(0, pos);
                }
                pos = value.IndexOf('<');
                if (pos != -1)
                {
                    value = value.Substring(0, pos);
                }
                i.Href = value;
                list.Add(i);

            }
            return list;
        }
Exemple #39
0
 //Tan solo para ver si el pregmatch tira lo que quiero
 public static string print_r_regex(MatchCollection mc)
 {
     string resp = "";
     if(mc.Count > 0)
     {
         resp += "Printing matches...";
         for(int i =0; i < mc.Count; i++)
         {
             resp += "\n";
             resp += "Match["+i+"]: " + mc[i].Value + "\n";
             resp += "Printing groups for this match...\n";
             GroupCollection gc = mc[i].Groups;
             for(int j =0; j < gc.Count; j++)
             {
                 resp += "\tGroup["+j+"]: "+ gc[j].Value + "\n";
                 resp += "\tPrinting captures for this group...\n";
                 CaptureCollection cc = gc[j].Captures;
                 for(int k =0; k < cc.Count; k++)
                 {
                     resp += "\t\tCapture["+k+"]: "+ cc[k].Value + "\n";
                 }
             }
         }
     }
     return resp;
 }
Exemple #40
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));
        }
Exemple #41
0
        public void WriterHtml(MatchCollection matches)
        {
            SuccessTotal = matches.Count;
            SuccessCurrent = 0;

            _strStream.Clear();
            _strStream.Append(File.OpenText("HTMLView/index2.txt").ReadToEnd());

            foreach (Match match in matches)
            {
                SuccessCurrent++;
                string time = match.Groups[1].Value;
                string name = match.Groups[2].Value;
                string content = match.Groups[3].Value;

                string timeTag = null;
                string contentTag = null;
                string nameTag = "<span class=\"name\">" + name + "</span>";

                bool owner = name == "회원님";
                string divClassName = (owner) ? "box box-mine" : "box box-enemy";


                _strStream.Append("<div class=\"" + divClassName + "\" >");

                _strStream.Append(nameTag);

                timeTag = "<span class=\"time\">" + time + "</span>";

                if (ImageFiles.ContainsKey(content))
                {
                    string imgPath = "image/" + content;
                    contentTag = "<a target=\"_blank/\" href=\"" + imgPath + "\" ><img class=\"img\" src=\"" + imgPath + "\"></img></a>";
                }
                else
                {
                    contentTag = "<p class=\"content\">" + HttpUtility.HtmlEncode(content) + "</p>";
                    // <br> 등의 Text를 &gt 화 하기 위함.
                }


                if (owner)
                {
                    _strStream.Append(timeTag);
                    _strStream.Append(contentTag);
                }
                else
                {
                    _strStream.Append(contentTag);
                    _strStream.Append(timeTag);
                }


                _strStream.Append("</div>");
            }
            

            _strStream.Append("</body></html>");
        }
Exemple #42
0
 public TextHighlighter(
     Page page,
     MatchCollection matches
     )
 {
     this.page = page;
     this.matchEnumerator = matches.GetEnumerator();
 }
 public AsynchronousRegex(int timeout)
 {
     _timeout = timeout;
     _sleepCounter = 0;
     _sleepInterval = 100;
     IsTimeout = false;
     _mc = null;
 }
 /// <summary>
 /// using a regular expression, find all of the href or urls 
 /// in the content of the page 
 /// </summary>
 /// <param name="content"></param>
 private void GetAllImagesUrls( string content )
 {
     //regular expression Responsible for finding all images on html document.
     string Pattern = @"(http://)[A-Za-z0-9\-\.]+\.[A-Za-z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s].(jpg|.png|.gif|.tiff)";
     Regex Regex = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
     Matches = Regex.Matches(content);
     ListOfDistinctMatches = Matches.Cast<Match>().Select(m => m.Value).Distinct().ToList();
 }
Exemple #45
0
 private void setPropertiesForReviewStar()
 {
     System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(this.Review, @"[0-9\.]+");
     if (matches.Count > 0)
     {
         this.ReviewStar = Convert.ToDecimal(matches[0].Value);
     }
 }
Exemple #46
0
 /// <summary>
 /// 处理html中的资源src
 /// </summary>
 /// <param name="html">html</param>
 /// <param name="page">page</param>
 /// <returns>html</returns>
 public string RePathJsCssImg(string html, BasePage page)
 {
     Matches = JsCssImageTest.Matches(html);
     html = ReplaceLinks(html, page);
     Matches = CssBgTest.Matches(html);
     html = ReplaceLinks(html, page);
     return html;
 }
 public bool Find ()
 {
     if (matches == null) {
         matches = regex.Matches (str);
         current = 0;
     }
     return (current < matches.Count);
 }
Exemple #48
0
        private static string formatMsoftMatches(Msoft.MatchCollection matches)
        {
            Msoft.Match[] matchArr = matches.Cast <Msoft.Match>().ToArray();

            return(string.Format("{0} matches: [{1}]",
                                 matchArr.Length,
                                 matchArr.Select(m => formatMsoftMatch(m))
                                 .JoinStrings()));
        }
Exemple #49
0
        private static void ShowMatches(string text, string regex)
        {
            Console.WriteLine("regex = {0}", regex);

            R.MatchCollection mc = R.Regex.Matches(text, regex);

            foreach (R.Match m in mc)
            {
                Console.WriteLine(m);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="inputTemplate"></param>
 private void SetOutputExtension(string inputTemplate)
 {
     System.Text.RegularExpressions.MatchCollection ma = System.Text.RegularExpressions.Regex.Matches(inputTemplate, @"<#@ output extension="".*?"" ");
     foreach (Match item in ma)
     {
         if (item.Success)
         {
             docExt = item.Value.Substring(item.Value.IndexOf(@"""")).Replace(@"""", "");
         }
     }
 }
    public static String GetEMailAddresses(string Input)
    {
        System.Text.RegularExpressions.MatchCollection MC = System.Text.RegularExpressions.Regex.Matches(Input, "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

        if (MC.Count > 0)
        {
            return(MC[0].Value);
        }

        return("");
    }
Exemple #52
0
        public static string[] CatchHtmlBlock(string content, string tag)
        {
            string findstr = string.Format(@"(?i)<{0}([^>])*>(\w|\W)*</{1}([^>])*>", tag, tag);

            System.Text.RegularExpressions.MatchCollection matchs = System.Text.RegularExpressions.Regex.Matches(content, findstr, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string[] strArray = new string[matchs.Count];
            for (int i = 0; i < strArray.Length; i++)
            {
                strArray[i] = matchs[i].Value;
            }
            return(strArray);
        }
 static public int get_IsReadOnly(IntPtr l)
 {
     try {
         System.Text.RegularExpressions.MatchCollection self = (System.Text.RegularExpressions.MatchCollection)checkSelf(l);
         pushValue(l, true);
         pushValue(l, self.IsReadOnly);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
            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));
            }
Exemple #55
0
            internal void build()
            {
                List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

                Dictionary <string, List <IMyTerminalBlock> > blocks = new Dictionary <string, List <IMyTerminalBlock> >();

                caller.GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(new List <IMyTerminalBlock>(), b => cacheBlock(b, blocks));
                foreach (var entry in blocks)
                {
                    SectionBlocks sec = new SectionBlocks(shipGrid, entry.Key, entry.Value);
                    sections.Add(sec.sectionName, sec);
                    sectionSorting.Add(sec.sectionName);
                }

                sectionSorting.Sort(new SectionComparator(sections));

                caller.GridTerminalSystem.GetBlocksOfType <IMyAirVent>(externalVents, b => b.CustomName.Contains(EXTERNAL_BLOCK_ID) && b.CubeGrid == caller.Me.CubeGrid);
                caller.GridTerminalSystem.GetBlocksOfType <IMyGasTank>(o2Tanks, b => b.CubeGrid == caller.Me.CubeGrid && (b.BlockDefinition.SubtypeName.ToLower().Contains("oxygen") || b.BlockDefinition.SubtypeName.ToLower().Contains("o2")));

                List <IMyDoor> li = new List <IMyDoor>();

                caller.GridTerminalSystem.GetBlocksOfType <IMyDoor>(li, b => b.CubeGrid == caller.Me.CubeGrid);
                foreach (IMyDoor door in li)
                {
                    if (isExternalDoor(door.CustomName))
                    {
                        externalDoors.Add(door);
                    }
                    else
                    {
                        System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(door.CustomName, INTERFACE_DOOR_SECTION_PATTERN);
                        if (mc != null && mc.Count > 0 && mc[0].Groups.Count > 0)
                        {
                            string   ids   = mc[0].Groups[1].ToString();
                            string[] parts = ids.Split(INTERFACE_DOOR_SECTION_SPLIT);
                            interDoors.Add(new InterfaceDoor(door, parts[0], parts[1]));
                        }
                        else
                        {
                            extraDoors.Add(door);
                        }
                    }
                }

                List <IMyTextPanel> li2 = new List <IMyTextPanel>();

                caller.GridTerminalSystem.GetBlocksOfType <IMyTextPanel>(li2, b => b.CustomName.Contains(DISPLAY_TAG) && b.CubeGrid == caller.Me.CubeGrid);
                foreach (IMyTextPanel scr in li2)
                {
                    displays.Add(new Display(scr));
                }
            }
Exemple #56
0
        private void RegexAA()
        {
            Regex  regex  = new Regex("[a-zA-Z]{2}");
            string str    = "3232Ab45cN34355ab";
            string result = "";

            System.Text.RegularExpressions.MatchCollection mc = regex.Matches(str);
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i].Value;
            }
            DialogResult dr = MessageBox.Show(result, "result");
        }
Exemple #57
0
        public static string Process(string s)
        {
            System.Text.RegularExpressions.MatchCollection ms =
                System.Text.RegularExpressions.Regex.Matches(s, @"[#]\w+[#]");

            for (int i = ms.Count - 1; i >= 0; i--)
            {
                System.Text.RegularExpressions.Match m = ms[i];
                string ID = m.Value.Remove(0, 1);
                s = s.Replace(m.Value, GetString(ID));
            }
            return(s);
        }
 static public int GetEnumerator(IntPtr l)
 {
     try {
         System.Text.RegularExpressions.MatchCollection self = (System.Text.RegularExpressions.MatchCollection)checkSelf(l);
         var ret = self.GetEnumerator();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #59
0
 //得到URL中的参数值
 public string GetUrlParam(string name, string url)
 {
     System.Text.RegularExpressions.Regex           re = new System.Text.RegularExpressions.Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?");
     System.Text.RegularExpressions.MatchCollection mc = re.Matches(url);
     foreach (System.Text.RegularExpressions.Match m in mc)
     {
         if (m.Result("$2").Equals(name))
         {
             return(m.Result("$3"));
         }
     }
     return("");
 }
Exemple #60
0
        /// <summary>
        /// 从字符串当中取得所有图片
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static List <string> GetImgsFromString(string info)
        {
            var result = new List <string>();

            if (!string.IsNullOrEmpty(info))
            {
                var reg =
                    new System.Text.RegularExpressions.Regex("<img[^>]+src=\"?([^>]*?)\"[^>]+/>",
                                                             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.Text.RegularExpressions.MatchCollection coll = reg.Matches(info);
                result.AddRange(from Match m in coll select m.Groups[1].Value);
            }
            return(result);
        }