NextMatch() 공개 메소드

public NextMatch ( ) : System.Text.RegularExpressions.Match
리턴 System.Text.RegularExpressions.Match
예제 #1
0
        private void fun_unknown()
        {
            string str = @"https://lbs.gtimg.com/maplbs/qianxi/00000000/37010006.js";

            WebClientto client = new WebClientto(4500);

            client.Encoding = Encoding.UTF8;
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            Stream stream   = null;
            string str_json = null;

            stream = client.OpenRead(str);

            str_json = new StreamReader(stream).ReadToEnd();

            Regex regexObj = new Regex(@"\[(?<result>)[^[\]]+\]");

            System.Text.RegularExpressions.Match matchResult = regexObj.Match(str_json);
            while (matchResult.Success)
            {
                MessageBox.Show(matchResult.Groups[0].Value);
                matchResult = matchResult.NextMatch();
            }
        }
예제 #2
0
파일: Node.cs 프로젝트: quwahara/Nana
 public static List<Node> Parse(ref Match m, string left, string right, string value)
 {
     List<Node> result;
     result = new List<Node>();
     while (m.Success)
     {
         // left, down
         if (m.Groups[left].Success)
         {
             m = m.NextMatch();
             Node tmp;
             tmp = new Node();
             tmp.Branches = Parse(ref m, left, right, value);
             result.Add(tmp);
         }
         else if (m.Groups[right].Success)
         {
             // right, up
             m = m.NextMatch();
             return result;
         }
         else if (m.Groups[value].Success)
         {
             // value, pluck
             Node tmp;
             tmp = new Node();
             tmp.Leaf = m.Groups[value].Value;
             result.Add(tmp);
             m = m.NextMatch();
         }
     }
     return result;
 }
        public string strMatch(string str, string pattern)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(str, pattern))
            {
                System.Text.RegularExpressions.Match m =
                    System.Text.RegularExpressions.Regex.Match(str, pattern);
                string v = "";
                //if (m.Success)
                //{
                //    v = str;

                //}
                while (m.Success)
                {
                    if (m.Value == ",")
                    {
                        v += m.Value;
                        continue;
                    }
                    v += m.Value;
                    m  = m.NextMatch();
                }
                return(str);
            }
            else
            {
                return(null);
            }
        }
예제 #4
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).ToString();
                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);
        }
예제 #5
0
        ///<summary>
        /// 从一段网页源码中获取正文
        ///</summary>
        ///<param name="input"></param>
        ///<returns></returns>
        public static string GetMainContent(string strinput)
        {
            string pattern = @"^[\u300a\u300b]|[\u4e00-\u9fa5]|[\uFF00-\uFFEF]";
            //string str = "dfa#445发了,. 。*(*&*^e4444";
            string v = "";

            if (System.Text.RegularExpressions.Regex.IsMatch(strinput, pattern))
            {
                //提示的代码在这里写
                System.Text.RegularExpressions.Match m =
                    System.Text.RegularExpressions.Regex.Match(strinput, pattern);
                while (m.Success)
                {
                    if (m.Value == ",")
                    {
                        v += m.Value;
                        continue;
                    }
                    v += m.Value;
                    m  = m.NextMatch();
                }
                //Response.Write(v);
            }
            v = v.Replace("微软雅黑", "").Replace("宋体", "").Replace("黑体", "");
            return(v);
        }
예제 #6
0
        public static void ParseHeader(ref Header header)
        {
            string hdr = System.Text.Encoding.ASCII.GetString(header.OriginalData);
            hdr = System.Text.RegularExpressions.Regex.Match(hdr, @"[\s\S]+?((?=\r?\n\r?\n)|\Z)").Value;
            hdr = Parser.Unfold(hdr);
            hdr = Codec.RFC2047Decode(hdr);
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(hdr, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");
            while(m.Success)
            {
                string name = FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':')));
                string value = m.Value.Substring(m.Value.IndexOf(":") + 1);
                if (name.Equals("received")) header.Trace.Add(Parser.ParseTrace(m.Value.Trim(' ')));
                else if (name.Equals("to")) header.To = Parser.ParseAddresses(value);
                else if (name.Equals("cc")) header.Cc = Parser.ParseAddresses(value);
                else if (name.Equals("bcc")) header.Bcc = Parser.ParseAddresses(value);
                else if (name.Equals("reply-to")) header.ReplyTo = Parser.ParseAddress(value);
                else if (name.Equals("from")) header.From = Parser.ParseAddress(value);
                else if (name.Equals("sender")) header.Sender = Parser.ParseAddress(value);
                else if (name.Equals("content-type")) header.ContentType = Parser.GetContentType(m.Value);
                else if (name.Equals("content-disposition")) header.ContentDisposition = Parser.GetContentDisposition(m.Value);

                header.HeaderFields.Add(name, value);
                header.HeaderFieldNames.Add(name, m.Value.Substring(0, m.Value.IndexOf(':')));
                m = m.NextMatch();
            }
        }
예제 #7
0
 private static ContentDisposition GetContentDisposition(string input)
 {
     ContentDisposition field = new ContentDisposition();
     field.Disposition = Regex.Match(input, @"(?<=: ?)\S+?(?=([;\s]|\Z))").Value;
     System.Text.RegularExpressions.Match parammatch = System.Text.RegularExpressions.Regex.Match(input, @"(?<=;[ \t]?)[^;]*=[^;]*(?=(;|\Z))");
     for (; parammatch.Success; parammatch = parammatch.NextMatch()) field.Parameters.Add(FormatFieldName(parammatch.Value.Substring(0, parammatch.Value.IndexOf('='))), parammatch.Value.Substring(parammatch.Value.IndexOf('=') + 1).Replace("\"", "").Trim('\r', '\n'));
     return field;
 }
예제 #8
0
        private void BuildSelection(string content, FlowDocument selectionDoc, Match m)
        {
            var p = new Paragraph();
            int lastPosition = 0;
            while (m.Success)
            {
                p.Inlines.Add(new Run(content.Substring(lastPosition, m.Index)));
                p.Inlines.Add(new Bold(new Run(content.Substring(m.Index, m.Length))));
                lastPosition = m.Index + m.Length;

                if (!m.NextMatch().Success)
                {
                    p.Inlines.Add(new Run(content.Substring(lastPosition, content.Length - lastPosition)));
                }

                selectionDoc.Blocks.Add(p);

                m = m.NextMatch();
            }
        }
예제 #9
0
 protected MatchViewModel(Match model)
 {
     Model = model;
     var groups = model.Groups;
     var capture = model.Captures;// Capture has Index, Length, Value
     var index = model.Index;
     var length = model.Length;
     var next = model.NextMatch();
     var result = model.Result(stringg);
     var x = model.Success;
     var y = model.Value;
     groups[0].
예제 #10
0
        private static string[] ParseDelimiters(Match match)
        {
            var delimiters = new List<string>();

            do
            {
                delimiters.Add(match.Groups["delimiter"].Value);
                match = match.NextMatch();
            }
            while (match.Success);

            return delimiters.ToArray();
        }
        public static List<string> GetTokenStringList(Match match, string token)
        {
            if (match.Success)
            {
                var matchList = new List<string>();

                matchList.Add(GetTokenString(match, token).Trim());

                do
                {
                    match = match.NextMatch();
                    matchList.Add(GetTokenString(match, token));
                } while (match.Success);

                return matchList;
            }
            return null;
        }
예제 #12
0
        /// <summary>
        /// DoFind is the helper for a regular Find (no proximity).  Very simple logic:
        /// Given a Regex Match, it will iterate through the match adding matches to
        /// the OberservableConcurrentDictionary
        /// </summary>
        /// <param name="match">The regex match based on the Find box text value</param>
        /// <param name="startRange">The Paragraph's start range - we need this for highlighting</param>
        /// <param name="endRange">The Paragraph's end range - we need this for highlighting</param>
        /// <param name="observableResults">The concurrent dictionary we are writing results to</param>
        public static void DoFind(SysRegex.Match match,
                                  int startRange,
                                  int endRange,
                                  OCDictionary observableResults)
        {
            while (match.Success)
            {
                // get actual match start and end range locations
                var beginRangeMatch = startRange + match.Index;
                var endRangeMatch   = beginRangeMatch + match.Length;

                // get some context for the match
                var beginContext = beginRangeMatch >= 5 ? (beginRangeMatch - 5) : beginRangeMatch;
                var endContext   = (endRangeMatch + 5) < endRange ? (endRangeMatch + 5) : endRange;
                FinderHelpers.AddResults(beginRangeMatch, endRangeMatch, beginContext, endContext, observableResults);

                match = match.NextMatch();
            }
        }
예제 #13
0
        public CompactRegexMatches(string input, Match match)
        {
            this.input = input;
            this.found = false;
            List<CompactRegexMatch> matchList = new List<CompactRegexMatch>();
            while (match.Success)
            {
                this.found = true;
                CompactRegexMatch regexMatch = new CompactRegexMatch();
                regexMatch.value = match.Value;
                bool firstGroup = true;
                bool secondGroup = true;
                StringBuilder sb = new StringBuilder();
                foreach (Group group in match.Groups)
                {
                    if (firstGroup)
                    {
                        firstGroup = false;
                        continue;
                    }

                    if (!secondGroup)
                        sb.Append(' ');
                    secondGroup = false;
                    sb.Append('(');

                    bool firstCapture = true;
                    foreach (Capture capture in group.Captures)
                    {
                        if (!firstCapture)
                            sb.Append(", ");
                        sb.AppendFormat("\"{0}\"", capture.Value);
                        firstCapture = false;
                    }
                    sb.Append(')');
                }
                regexMatch.groups = sb.ToString();
                matchList.Add(regexMatch);
                match = match.NextMatch();
            }
            matches = matchList.ToArray();
        }
예제 #14
0
        private object MatchString(string text)
        {
            System.Text.RegularExpressions.Match match = this.regex.Match(text);
            Type type = (this.memberInfo is FieldInfo) ? ((FieldInfo)this.memberInfo).FieldType : ((PropertyInfo)this.memberInfo).PropertyType;

            if (type.IsArray)
            {
                ArrayList list = new ArrayList();
                for (int i = 0; match.Success && (i < this.maxRepeats); i++)
                {
                    if (match.Groups.Count <= this.group)
                    {
                        throw BadGroupIndexException(this.group, this.memberInfo.Name, match.Groups.Count - 1);
                    }
                    Group group = match.Groups[this.group];
                    foreach (Capture capture in group.Captures)
                    {
                        list.Add(text.Substring(capture.Index, capture.Length));
                    }
                    match = match.NextMatch();
                }
                return(list.ToArray(typeof(string)));
            }
            if (match.Success)
            {
                if (match.Groups.Count <= this.group)
                {
                    throw BadGroupIndexException(this.group, this.memberInfo.Name, match.Groups.Count - 1);
                }
                Group group2 = match.Groups[this.group];
                if (group2.Captures.Count > 0)
                {
                    if (group2.Captures.Count <= this.capture)
                    {
                        throw BadCaptureIndexException(this.capture, this.memberInfo.Name, group2.Captures.Count - 1);
                    }
                    Capture capture2 = group2.Captures[this.capture];
                    return(text.Substring(capture2.Index, capture2.Length));
                }
            }
            return(null);
        }
예제 #15
0
        /// <summary>
        /// 取得每个定义公式的最小单元
        /// </summary>
        /// <param name="s">审核公式左或右部分字符串</param>
        /// <returns>List 公式最小单元</returns>
        private static List <string> SplitChkUnit(string s)
        {
            try
            {
                List <string> l = new List <string>();

                string pattern = @"[^+\-*/()]+";
                System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(s, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);

                while (match.Success)
                {
                    l.Add(match.Value);
                    match = match.NextMatch();
                }
                return(l);
            }
            catch (Exception ex)
            {
                throw new Exception("公式定义错!请检查公式!" + ex.Message);
            }
        }
예제 #16
0
 private void ReadEntity()
 {
     matchEnts = regexEnts.Match(content);
     while (matchEnts.Success)
     {
         CBEntity.Items.Add(matchEnts.Groups[1].Value.ToString());
         matchEnts = matchEnts.NextMatch();
     }
     if (CBEntity.Items.Count > 0)
     {
         CBEntity.SelectedIndex = CBEntity.Items.Count - 1;
         CBEntity.IsEnabled = true;
         BOk.IsEnabled = true;
     }
     else
     {
         MessageBox.Show("Entity не обнаружены.");
         CBEntity.IsEnabled = false;
         BOk.IsEnabled = false;
     }
 }
        protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match)
        {
            var matchState = 0;
            while (match.Success)
            {
                var groupCollection = match.Groups;
                if (matchState == 0)
                {
                    foreach (var key in RegSplitForAll.GetGroupNames())
                    {
                            int tmp;
                            matchState = 1;
                            if (int.TryParse(key, out tmp)) continue;
                            int fieldBufferKey;
                            if (context.SourceHeaderInfo.TryGetValue(key, out fieldBufferKey))
                            context.FieldBuffer[context.SourceHeaderInfo[key]] = groupCollection[key].Value;

                    }
                    match = match.NextMatch();
                }
                else
                {
                    if (context.SourceHeaderInfo.ContainsKey(match.Groups[4].Value))
                    context.FieldBuffer[context.SourceHeaderInfo[match.Groups[4].Value]] = match.Groups[5].Value;
                    match = match.NextMatch();
                }

            }

            return NextInstruction.Return;
        }
예제 #18
0
        // Three very similar algorithms appear below: replace (pattern),
        // replace (evaluator), and split.

        /// <summary>
        /// Replaces all occurrences of the regex in the string with the
        /// replacement pattern.
        ///
        /// Note that the special case of no matches is handled on its own:
        /// with no matches, the input string is returned unchanged.
        /// The right-to-left case is split out because StringBuilder
        /// doesn't handle right-to-left string building directly very well.
        /// </summary>
        public string Replace(Regex regex, string input, int count, int startat)
        {
            if (count < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
            }
            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
            }

            if (count == 0)
            {
                return(input);
            }

            Match match = regex.Match(input, startat);

            if (!match.Success)
            {
                return(input);
            }
            else
            {
                StringBuilder sb = StringBuilderCache.Acquire();

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    do
                    {
                        if (match.Index != prevat)
                        {
                            sb.Append(input, prevat, match.Index - prevat);
                        }

                        prevat = match.Index + match.Length;
                        ReplacementImpl(sb, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat < input.Length)
                    {
                        sb.Append(input, prevat, input.Length - prevat);
                    }
                }
                else
                {
                    List <string> al     = new List <string>();
                    int           prevat = input.Length;

                    do
                    {
                        if (match.Index + match.Length != prevat)
                        {
                            al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));
                        }

                        prevat = match.Index;
                        ReplacementImplRTL(al, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat > 0)
                    {
                        sb.Append(input, 0, prevat);
                    }

                    for (int i = al.Count - 1; i >= 0; i--)
                    {
                        sb.Append(al[i]);
                    }
                }

                return(StringBuilderCache.GetStringAndRelease(sb));
            }
        }
예제 #19
0
        private static IEnumerable<Match> EnumerateMatches(Match match, int count)
        {
            while (match.Success)
            {
                yield return match;

                count--;

                if (count == 0)
                    yield break;

                match = match.NextMatch();
            }
        }
예제 #20
0
    // 匹配操作
    IEnumerator handleMatch_plus(string _Regex, DrugItem item, MatchResult.Type type)
    {
        yield return(new WaitForEndOfFrame());

        var r = new System.Text.RegularExpressions.Regex(_Regex);

        System.Text.RegularExpressions.Match m = null;
        string matchstring = string.Empty;
        string contentText = string.Empty;

        switch (type)
        {
        case MatchResult.Type.Class:
        case MatchResult.Type.Drug:
        {
            matchstring = item.Name;
            if (matchstring != string.Empty)
            {
                m = r.Match(matchstring);
            }
            if (item.JsonData != null && item.JsonData.IsObject)
            {
            }
        }
        break;

        case MatchResult.Type.Extract_Class:
        case MatchResult.Type.Extract_Drug:
        {
            JsonData jd = null;
            if (type == MatchResult.Type.Extract_Drug)
            {
                jd = item.JsonData["知识点"];
            }
            else
            {
                jd = item.JsonData["信息详情"];
            }
            if (jd != null)
            {
                var zishenjiegou  = jd["自身结构"];
                var shiyingzheng  = jd["适应症"];
                var zhuyishixiang = jd["注意事项"];
                var other1        = jd["其他1"];
                var other2        = jd["其他2"];
                if (zishenjiegou != null)
                {
                    foreach (var v in zishenjiegou)
                    {
                        matchstring += v.ToString();
                    }
                }
                if (shiyingzheng != null)
                {
                    foreach (var v in shiyingzheng)
                    {
                        matchstring += v.ToString();
                    }
                }
                if (zhuyishixiang != null)
                {
                    foreach (var v in zhuyishixiang)
                    {
                        matchstring += v.ToString();
                    }
                }
                if (other1 != null)
                {
                    matchstring += other1.ToString();
                }
                if (other2 != null)
                {
                    matchstring += other2.ToString();
                }
                if (matchstring != string.Empty)
                {
                    m = r.Match(matchstring);
                }
            }
        }
        break;
        }
        while (matchstring != string.Empty && m != null && m.Success)
        {
            if (_Regex.Length - 3 > m.Length)
            {
                m = m.NextMatch();
                continue;
            }
            Debug.Log(" 成功匹配到内容:name=" + item.Name + " type=" + type + " matchString=" + (matchstring.Length > 4 ? matchstring.Substring(0, 3) + "..." : matchstring) + " regex=" + _Regex + " index=" + m.Index + " length=" + m.Length + " value=" + m.Value);

            // 添加匹配数据
            var im = new MatchResult.MatchItem.Item();
            im.Index  = m.Index;
            im.Length = m.Length;
            im.Value  = m.Value;

            var mr = MainJsonData.MatchResultList.Find((mresult) => { return(mresult.Name == item.Name); });
            if (mr == null)
            {
                mr      = new MatchResult();
                mr.Name = item.Name;
                foreach (var str in item.InfoTextList)
                {
                    mr.ContentText += str;
                }
                MainJsonData.MatchResultList.Add(mr);
            }
            var mItem = mr.MatchItemList.Find((mi) => { return(mi.MatchString == matchstring && mi.MResultType == type); });
            if (mItem == null)
            {
                mItem             = new MatchResult.MatchItem();
                mItem.MatchString = matchstring;
                mItem.MResultType = type;
                mr.MatchItemList.Add(mItem);
            }
            mItem.ItemList.Add(im);

            m = m.NextMatch();
        }

        // 检查是否匹配完成
        if (index < MainJsonData.Total_Drug_And_Class_Count * 2)
        {
            lock (asynclockobj)
            {
                if (index < MainJsonData.Total_Drug_And_Class_Count * 2)
                {
                    ++index;
                    if (index == MainJsonData.Total_Drug_And_Class_Count * 2)
                    {
                        Debug.Log(" 匹配操作已经完成! 一共执行" + index + "次匹配!");
                        Debug.Log(" 匹配结果总数=" + MainJsonData.MatchResultList.Count);

                        matchSort();

                        UpdateMatchUI();
                        index = 0;
                    }
                    else
                    {
                        // Debug.Log(" 匹配操作中... 正在执行第" + index + "次匹配!");
                    }
                }
            }
        }
    }
예제 #21
0
        //big surprise!!! the official entrance is the encoding with s-jis of county's name, BUT, shop's name also works! And now I use shop's name with others' will narely do
        //And the response body between them are 3 lines:
        //<a href="http://aksale.advs.jp/cp/akachan_sale_pc/search_event_detail.cgi?event_id=9782391339&area1=&area2=北海道&area3=&event_open_date=201510&kmws=">
        //<a href="http://aksale.advs.jp/cp/akachan_sale_pc/search_event_detail.cgi?event_id=9782391339&area1=&area2=旭川店&area3=&event_open_date=201510&kmws=">
        //<a href="http://aksale.advs.jp/cp/akachan_sale_pc/search_event_detail.cgi?event_id=5637179822&area1=&area2=北海道&area3=&event_open_date=201510&kmws=">
        //<a href="http://aksale.advs.jp/cp/akachan_sale_pc/search_event_detail.cgi?event_id=5637179822&area1=&area2=旭川店&area3=&event_open_date=201510&kmws=">
        //<a href="./search_shop_list.cgi?event_type=6&area1=&area2=%96k%8aC%93%b9&area3=&kmws=">戻る</a>
        //<a href="./search_shop_list.cgi?event_type=6&area1=&area2=%88%ae%90%ec%93X&area3=&kmws=">戻る</a>
        public int probe(string county, string shop)
        {
            string respHtml = Form1.weLoveYue(
                form1,
                "http://aksale.advs.jp/cp/akachan_sale_pc/search_event_list.cgi?area2=" + county + "&event_type=" + sizeType + "&sid=" + shop + "&kmws=",

                "GET", "", true, "", ref  cookieContainer,
                false
                );

            if (respHtml.Equals("Found"))
            {
                form1.setLogT("CardNo" + appointment.CardNo + ", first GET eccur an error!");
               //         return -1;
            }

            //       <input type="submit" name="sbmt" value="予約" >
            rgx = @"<input type=""submit"" name=""sbmt"" value=""";
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (!myMatch.Success)
            {
                form1.setLogT("CardNo" + appointment.CardNo + ", no available appointment.");
                return -5;// no available appointment
            }

            if (respHtml.Contains("eventId") && !respHtml.Contains("captcha"))
            {
                rgx = @"(?<=\[\]\,{""eventId"":)\d+?(?=\,)";  //there will be no veri code
                requireVeriCode = false;
            }
            else
            {
                rgx = @"(?<=予約"" >\n.+event_id"" value="")\d+?(?="")";  //there will be a veri code, and we can cheeck up with captcha
                //name="event_id" value="2543729870"
                requireVeriCode = true;
            }
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (myMatch.Success)
            {
                eventId = myMatch.Groups[0].Value;
            }

            //one day's book in one card, for gong cheng county
            myMatch = myMatch.NextMatch();
            while (myMatch.Success)
            {
                PaperDiaper paper = new PaperDiaper(form1, appointment, mail, county, shop , myMatch.Groups[0].Value, requireVeriCode);
                Thread t = new Thread(paper.multiBook);
                t.Start();
                myMatch = myMatch.NextMatch();
            }

            if (!respHtml.Contains("captcha"))//        daiyyr
            {
                // jump to verification
            }
            else
            {

                //post eventId to get the verification code page
                respHtml = Form1.weLoveYue(
                form1,
                "http://aksale.advs.jp/cp/akachan_sale_pc/captcha.cgi",
                "POST",
                "http://aksale.advs.jp/cp/akachan_sale_pc/search_event_list.cgi?area2=" + county + "&event_type=" + sizeType + "&sid=" + shop + "&kmws=",
                false,
                "sbmt=%97%5C%96%F1&event_id="+eventId+"&event_type=6",
               ref  cookieContainer,
                false
                );

                //show verification code

                //<img src="./captcha/144445570520561.jpeg" alt="画像認証" /><br />
                //http://aksale.advs.jp/cp/akachan_sale_pc/captcha/144445570520561.jpeg

                string cCodeGuid = "";
                rgx = @"(?<=img src=""\./captcha/)\d+?(?=\.jpeg)";
                myMatch = (new Regex(rgx)).Match(respHtml);
                if (myMatch.Success)
                {
                    cCodeGuid = myMatch.Groups[0].Value;
                }
                lock (form1.pictureBox1)
                {

                    if (form1.textBox2.InvokeRequired)
                    {
                        delegate2 sl = new delegate2(delegate()
                        {
                            form1.pictureBox1.ImageLocation = @"http://aksale.advs.jp/cp/akachan_sale_pc/captcha/" + cCodeGuid + ".jpeg";
                            form1.textBox2.Text = "";
                            form1.textBox2.ReadOnly = false;
                            form1.textBox2.Focus();
                            form1.label9.Text = "cardNo" + appointment.CardNo + ":请输入验证码";
                            form1.label9.Visible = true;
                        });
                        form1.textBox2.Invoke(sl);
                    }
                    else
                    {
                        form1.pictureBox1.ImageLocation = @"http://aksale.advs.jp/cp/akachan_sale_pc/captcha/" + cCodeGuid + ".jpeg";
                        form1.textBox2.Text = "";
                        form1.textBox2.ReadOnly = false;
                        form1.textBox2.Focus();
                        form1.label9.Text = "cardNo" + appointment.CardNo + ":请输入验证码";
                        form1.label9.Visible = true;
                    }

                    while (form1.textBox2.Text.Length < 5)
                    {
                        Thread.Sleep(30);
                    }

                    verificationCode = form1.textBox2.Text.Substring(0, 5);
                    if (form1.textBox2.InvokeRequired)
                    {
                        delegate2 sl = new delegate2(delegate()
                        {
                            form1.textBox2.ReadOnly = true;
                            form1.label9.Visible = false;
                            form1.pictureBox1.ImageLocation = @"";
                        });
                        form1.textBox2.Invoke(sl);
                    }
                    else
                    {
                        form1.textBox2.ReadOnly = true;
                        form1.label9.Visible = false;
                        form1.pictureBox1.ImageLocation = @"";
                    }
                }// end of lock picturebox1

                //submit the veri code
                respHtml = Form1.weLoveYue(
                form1,
                "http://aksale.advs.jp/cp/akachan_sale_pc/_mail.cgi",
                "POST",
                "http://aksale.advs.jp/cp/akachan_sale_pc/captcha.cgi",
                false,
                "input_captcha=" + verificationCode + "&sbmt=%8E%9F%82%D6&event_id=" + eventId + "&event_type=" + sizeType ,
               ref  cookieContainer,
                false
                );

                while (respHtml.Contains("captcha"))
                {
                    form1.setLogT("CardNo" + appointment.CardNo + ", 验证码错误!请重新输入");
                    rgx = @"(?<=img src=""\./captcha/)\d+?(?=\.jpeg)";
                    myMatch = (new Regex(rgx)).Match(respHtml);
                    if (myMatch.Success)
                    {
                        cCodeGuid = myMatch.Groups[0].Value;
                    }
                    lock (form1.pictureBox1)
                    {

                        if (form1.textBox2.InvokeRequired)
                        {
                            delegate2 sl = new delegate2(delegate()
                            {
                                form1.pictureBox1.ImageLocation = @"http://aksale.advs.jp/cp/akachan_sale_pc/captcha/" + cCodeGuid + ".jpeg";
                                form1.textBox2.Text = "";
                                form1.textBox2.ReadOnly = false;
                                form1.textBox2.Focus();
                                form1.label9.Text = "CardNo" + appointment.CardNo + ":请输入验证码";
                                form1.label9.Visible = true;
                            });
                            form1.textBox2.Invoke(sl);
                        }
                        else
                        {
                            form1.pictureBox1.ImageLocation = @"http://aksale.advs.jp/cp/akachan_sale_pc/captcha/" + cCodeGuid + ".jpeg";
                            form1.textBox2.Text = "";
                            form1.textBox2.ReadOnly = false;
                            form1.textBox2.Focus();
                            form1.label9.Text = "CardNo" + appointment.CardNo + ":请输入验证码";
                            form1.label9.Visible = true;
                        }

                        while (form1.textBox2.Text.Length < 5)
                        {
                            Thread.Sleep(30);
                        }

                        verificationCode = form1.textBox2.Text.Substring(0, 5);
                        if (form1.textBox2.InvokeRequired)
                        {
                            delegate2 sl = new delegate2(delegate()
                            {
                                form1.textBox2.ReadOnly = true;
                                form1.label9.Visible = false;
                                form1.pictureBox1.ImageLocation = @"";
                            });
                            form1.textBox2.Invoke(sl);
                        }
                        else
                        {
                            form1.textBox2.ReadOnly = true;
                            form1.label9.Visible = false;
                            form1.pictureBox1.ImageLocation = @"";
                        }
                    }// end of lock picturebox1

                    //submit the veri code
                    respHtml = Form1.weLoveYue(
                    form1,
                    "http://aksale.advs.jp/cp/akachan_sale_pc/_mail.cgi",
                    "POST",
                    "http://aksale.advs.jp/cp/akachan_sale_pc/captcha.cgi",
                    false,
                    "input_captcha=" + verificationCode + "&sbmt=%8E%9F%82%D6&event_id=" + eventId + "&event_type=" + sizeType,
                    ref cookieContainer,
                    false
                    );

                }//end of while wrong code
            }//end of if need vervification code

            //post email
            respHtml = Form1.weLoveYue(
                form1,
                "https://aksale.advs.jp/cp/akachan_sale_pc/mail_form.cgi"
                ,
                "POST",
                requireVeriCode ? "http://aksale.advs.jp/cp/akachan_sale_pc/_mail.cgi" :
                ("http://aksale.advs.jp/cp/akachan_sale_pc/_mail.cgi?sbmt=%97%5C%96%F1&event_id=" + eventId + "&event_type=" + sizeType)
                ,
                false,
                "mail1=" + mail.address.Replace("@", "%40") + "&mail2=" + mail.address.Replace("@", "%40") + "&sbmt=%8E%9F%82%D6&event_id=" + eventId + "&event_type=" + sizeType,
              //    "mail1=15985830370%40163.com&mail2=15985830370%40163.com&sbmt=%8E%9F%82%D6&event_id=5393381489&event_type=6"
                ref cookieContainer,
                false
                );

            //post email again
            respHtml = Form1.weLoveYue(
                form1,
                "https://aksale.advs.jp/cp/akachan_sale_pc/mail_confirm.cgi"
                ,
                "POST",
                "https://aksale.advs.jp/cp/akachan_sale_pc/mail_form.cgi",
                false,
                "sbmt=%91%97%90M&mail1=" + mail.address.Replace("@", "%2540").Replace(".", "%252e") + "&mail2=" + mail.address.Replace("@", "%2540").Replace(".", "%252e") + "&event_id=" + eventId + "&event_type=" + sizeType ,
              //    sbmt=%91%97%90M&mail1=15985830370%2540163%252ecom&mail2=15985830370%2540163%252ecom&event_id=7938283049&event_type=6
                ref cookieContainer,
                false
              );

            if (respHtml.Contains("下記メールアドレスにメールを送信しました"))
            {
                form1.setLogT("CardNo" + appointment.CardNo+ ", step1 succeed, checking email: " + mail.address);
            }
            else
            {
                form1.setLogtRed("CardNo" + appointment.CardNo + ", appointments closed: " + mail.address);
                return -1;
            }

            keyURL = mail.queery("ご注文予約案内", @"https://aksale(\s|\S)+?(?=\r)");
            if (keyURL == null | keyURL == "")
            {
                form1.setLogT("NULL url from email");
            }
            setAppointment(mail.address, keyURL);

            return 1;
        }
        public int StringToInt(string str)
        {
            int x = 0;

            if (str == null)
            {
                return(x);
            }
            for (System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(str, @"\d+"); match.Success; match = match.NextMatch())
            {
                x = int.Parse(match.Value, System.Globalization.NumberFormatInfo.InvariantInfo);
            }

            return(x);
        }
 protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match)
 {
     if (!match.Success) return NextInstruction.Skip;
     var datetime = false;
     while (match.Success)
     {
         if (!datetime) context.FieldBuffer[context.SourceHeaderInfo["Datetime"]] = match.Groups["Datetime"].Value;
         datetime = true;
         if (context.SourceHeaderInfo.ContainsKey(match.Groups[5].Value))
             context.FieldBuffer[context.SourceHeaderInfo[match.Groups[5].Value]] = match.Groups[8].Value;
         match = match.NextMatch();
     }
     return NextInstruction.Return;
 }
예제 #24
0
파일: Class1.cs 프로젝트: tiger31/PlayerSys
        public void ParseSkillsFromString(string skillSave)
        {
            match1 = first.Match(skillSave);
            int i = 1;
            while (match1.Success) {
                Console.WriteLine("Match" + (i + 1));
                if (match1.Groups[1].Value != "" && match1.Groups[1].Value != null) {
                    //Создание верменного массива и увеличение основного на одну ячеку
                    Array.Resize<Skill>(ref skillArr, i);

                    //Задание строковых переменных
                    string name = match1.Groups[1].Value;
                    string type = match1.Groups[3].Value;

                    bool avalible;

                    int maxLevel;

                    SkillData baseS = new SkillData();
                    SkillData perL = new SkillData();

                    //Первый блок try, в котором задаются такие переменные, как avalible, level и maxlevel
                    try {
                        int j = int.Parse(match1.Groups[2].Value);
                        if (j == 0)
                            avalible = false;
                        else
                            avalible = true;
                        maxLevel = int.Parse(match1.Groups[4].Value);
                    } catch (FormatException e) {
                        Console.WriteLine("Some errors while parsing data" + e.Message);
                        avalible = false;
                        maxLevel = 0;
                    }
                    //Начало второго цикла регулярных выражений
                    match2 = second.Match(match1.Groups[5].Value);
                    //Считывание значений перезарядки
                    try {
                        baseS.cd = double.Parse(match2.Groups[1].Value);
                        if (match2.Groups[2].Value == "+")
                            perL.cd = double.Parse(match2.Groups[3].Value);
                        else
                            perL.cd = double.Parse(match2.Groups[3].Value) * -1;
                    } catch (FormatException e) {
                        Console.WriteLine("Some errors while parsing data" + e.Message);
                    }
                    match2 = match2.NextMatch();
                    //Считывание значений стоимости умения
                    try {
                        baseS.cost = double.Parse(match2.Groups[1].Value);
                        if (match2.Groups[2].Value == "+")
                            perL.cost = double.Parse(match2.Groups[3].Value);
                        else
                            perL.cost = double.Parse(match2.Groups[3].Value) * -1;
                    } catch (FormatException e) {
                        Console.WriteLine("Some errors while parsing data" + e.Message);
                    }
                    match2 = match2.NextMatch();
                    //Считывание значений длительности
                    try {
                        baseS.duration = double.Parse(match2.Groups[1].Value);
                        if (match2.Groups[2].Value == "+")
                            perL.duration = double.Parse(match2.Groups[3].Value);
                        else
                            perL.duration = double.Parse(match2.Groups[3].Value) * -1;
                    } catch (FormatException e) {
                        Console.WriteLine("Some errors while parsing data" + e.Message);
                    }
                    //Конец считывания по второму регулярному выражению

                    //Задание ранее считанных параметров новому умению
                    skillArr[i - 1] = new Skill(name, avalible, type, maxLevel, baseS, perL);
                }
                i++;
                match1 = match1.NextMatch();
            }
        }
예제 #25
0
        /// <summary>
        /// Parses the message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static Message ParseMessage(byte[] data)
        {
            //string msg = System.Text.Encoding.ASCII.GetString(data);
#if !PocketPC
            string msg = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
#else
            string msg = Pop3Client.PPCEncode.GetString(data, 0, data.Length);
#endif

            Message message = new Message();

            try
            {
                // Build a part tree and get all headers.
                MimePart part = ParseMimePart(msg, message);

                // Fill a new message object with the new information.
                message.OriginalData     = data;
                message.HeaderFields     = part.HeaderFields;
                message.HeaderFieldNames = part.HeaderFieldNames;

                // Dispatch header fields to corresponding object.
                foreach (string key in message.HeaderFields.AllKeys)
                {
                    string name  = key;
                    string value = message.HeaderFields[key];
                    if (name.Equals("received"))
                    {
                        System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(value, @"from.+?(?=(from|$))");
                        while (m.Success)
                        {
                            message.Trace.Add(Parser.ParseTrace(key + ": " + m.Value));
                            m = m.NextMatch();
                        }
                    }
                    else if (name.Equals("to"))
                    {
                        message.To = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("cc"))
                    {
                        message.Cc = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("bcc"))
                    {
                        message.Bcc = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("reply-to"))
                    {
                        message.ReplyTo = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("from"))
                    {
                        message.From = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("sender"))
                    {
                        message.Sender = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("content-type"))
                    {
                        message.ContentType = Parser.GetContentType(key + ": " + value);
                    }
                    else if (name.Equals("content-disposition"))
                    {
                        message.ContentDisposition = Parser.GetContentDisposition(key + ": " + value);
                    }
                    else if (name.Equals("domainkey-signature"))
                    {
                        message.Signatures.DomainKeys = Signature.Parse(key + ": " + value, message);
                    }
                }

                if (message.ContentType.MimeType.Equals("application/pkcs7-mime") ||
                    message.ContentType.MimeType.Equals("application/x-pkcs7-mime"))
                {
                    if (message.ContentType.Parameters["smime-type"] != null &&
                        message.ContentType.Parameters["smime-type"].Equals("enveloped-data"))
                    {
                        message.IsSmimeEncrypted = true;
                    }
                    if (message.ContentType.Parameters["smime-type"] != null &&
                        message.ContentType.Parameters["smime-type"].Equals("signed-data"))
                    {
                        message.HasSmimeSignature = true;
                    }
                }

                if (message.ContentType.MimeType.Equals("multipart/signed"))
                {
                    message.HasSmimeDetachedSignature = true;
                }

                // Keep a reference to the part tree within the new Message object.
                message.PartTreeRoot = part;

                DispatchParts(ref message);

                // Dispatch the part tree content to the appropriate collections and properties.
                // TODO
            }
            catch (Exception ex)
            {
                if (ErrorParsing != null)
                {
                    ErrorParsing(null, ex);
                }
            }
            return(message);
        }
예제 #26
0
        public static string getImages(string Url, string html)
        {
            string str   = "";
            string lower = "";
            string str1  = "";

            for (System.Text.RegularExpressions.Match i = (new Regex("<IMG[^>]+src=\\s*(?:'(?<src>[^']+)'|\"(?<src>[^\"]+)\"|(?<src>[^>\\s]+))\\s*[^>]*>", RegexOptions.IgnoreCase)).Match(html); i.Success; i = i.NextMatch())
            {
                lower = i.Groups["src"].Value.ToLower();
                if (lower.IndexOf("http") != 0)
                {
                    string[] strArrays = Url.Trim().Split(new char[] { '/' });
                    try
                    {
                        str1 = ((int)strArrays.Length <= 3 ? Url.Trim() : Url.Trim().Replace(strArrays[(int)strArrays.Length - 1], ""));
                    }
                    catch
                    {
                        str1 = Url.Trim();
                    }
                    str = (lower.IndexOf("/") != 0 ? string.Concat(str, i.Value.Replace(i.Groups["src"].Value, string.Concat(str1, i.Groups["src"].Value)), "<br/>") : string.Concat(str, i.Value.Replace(i.Groups["src"].Value, string.Concat("http://", strArrays[2], i.Groups["src"].Value)), "<br/>"));
                }
                else
                {
                    str = string.Concat(str, i.Value, "<br />");
                }
            }
            return(str);
        }
예제 #27
0
        ///// <summary>
        ///// RESERVE / BAUSTELLE
        ///// Bisher musste ich keinen PIN eingeben, da SIM-Karte ohne PIN-Sperre
        ///// </summary>
        ///// <param name="PIN"></param>
        //private void SetPinCode(string PIN)
        //{
        //    //https://www.smssolutions.net/tutorials/gsm/sendsmsat/
        //    //AT-Commands_Samba75 Manual Seite 72ff.

        //    string result = ExecCommand("AT+CPIN?", 300, "Failed to set PIN.");
        //    if (result.EndsWith("\r\nOK\r\n")) return;
        //    {
        //        ExecCommand("AT+CPIN=\"" + PIN + "\"", 300, "Failed to set PIN.");
        //        Syste.Threading.Thread.Sleep(5000);
        //    }
        //}

        public static MessageCollection ParseMessages(string input)
        {
            if (input.Length == 0)
            {
                return(null);
            }

            // Log.Text(Log.Type.Internal, input+"#################");

            MessageCollection messages = new MessageCollection();

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\\+CMGL: (\\d+),\"(.+)\",\"(.+)\",(.*),\"(.+)\"\\r\\n(.+)"); // "\\+CMGL: (\\d+),\"(.+)\",\"(.+)\",(.*),\"(.+)\"\n(.+)\n\n\""
            System.Text.RegularExpressions.Match m = r.Match(input);

            while (m.Success)
            {
                //string gr0 = m.Groups[0].Value; // <alles>
                string gr1 = m.Groups[1].Value;                   //6
                string gr2 = m.Groups[2].Value;                   //STO SENT
                string gr3 = m.Groups[3].Value;                   //+49123456789
                //string gr4 = m.Groups[4].Value; // -LEER-
                string gr5 = m.Groups[5].Value.Replace(',', ' '); //18/09/28,11:05:51 + 105
                string gr6 = m.Groups[6].Value;                   //Nachricht
                string gr7 = m.Groups[7].Value;                   //Nachricht (notwendig?)

                //MessageBox.Show(string.Format("0:{0}\r\n1:{1}\r\n2:{2}\r\n3:{3}\r\n4:{4}\r\n5:{5}\r\n6:{6}\r\n7:{7}\r\n", gr0, gr1, gr2, gr3, gr4, gr5, gr6, gr7), "Rohdaten");

                int.TryParse(gr1, out int smsId);
                DateTime.TryParse(gr5, out DateTime time);

                //MessageBox.Show("Zeit interpretiert: " + time.ToString("dd.MM.yyyy HH:mm:ss"));

                //Message Status zu MessageType
                MessageType type;
                switch (gr2)
                {
                case "REC UNREAD":
                case "REC READ":
                    type = MessageType.RecievedFromSms;
                    break;

                case "STO SENT":
                    type = MessageType.SentToSms;
                    break;

                default:
                    type = MessageType.RecievedFromSms;
                    break;
                }

                //Nachricht erstellen
                Message msg = new Message
                {
                    Index  = smsId,
                    Status = gr2,
                    //Alphabet -leer-
                    Type            = (ushort)type,
                    Cellphone       = HelperClass.ConvertStringToPhonenumber(gr3),
                    SentTime        = Sql.ConvertToUnixTime(time),
                    CustomerKeyWord = GetKeyWords(gr6),
                    Content         = gr6 + gr7
                };

                messages.Add(msg);

                m = m.NextMatch();
            }

            return(messages);
        }
예제 #28
0
 private void GetCuptionsResult(Match m, Hashtable groups, StringCollection resultValues) {
     string captionResultPattern = _regexControl.CurrentPattern.Result;
     bool hasCaptionResultPattern = captionResultPattern != null && captionResultPattern.Length > 0;
     _groupTitlesList = new StringCollection();
     while (m.Success) {
         if (hasCaptionResultPattern)
             resultValues.Add(m.Result(captionResultPattern));
         int i = 0;
         foreach (Group group in m.Groups) {
             if (i == 0) {
                 i++;
                 continue;
             }
             string groupTitle = string.Format(MsgsBase.Res.Group_No, i++);
             if (!groups.Contains(groupTitle))
                 groups.Add(groupTitle, new ArrayList());
             if (!_groupTitlesList.Contains(groupTitle))
                 _groupTitlesList.Add(groupTitle);
             IList captures = new StringCollection();
             ((IList) groups[groupTitle]).Add(captures);
             foreach (Capture c1 in group.Captures)
                 captures.Add(c1.Value);
         }
         m = m.NextMatch();
     }
 }
예제 #29
0
        public static void RegexUnicodeChar()
        {
            // Regex engine is Unicode aware now for the \w and \d character classes
            // \s is not - i.e. it still only recognizes the ASCII space separators, not Unicode ones
            // The new character classes for this:
            // [\p{L1}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]
            List <char> validChars   = new List <char>();
            List <char> invalidChars = new List <char>();

            for (int i = 0; i < MaxUnicodeRange; i++)
            {
                char c = (char)i;
                switch (CharUnicodeInfo.GetUnicodeCategory(c))
                {
                case UnicodeCategory.UppercaseLetter:            //Lu
                case UnicodeCategory.LowercaseLetter:            //Li
                case UnicodeCategory.TitlecaseLetter:            // Lt
                case UnicodeCategory.ModifierLetter:             // Lm
                case UnicodeCategory.OtherLetter:                // Lo
                case UnicodeCategory.DecimalDigitNumber:         // Nd
                //                    case UnicodeCategory.LetterNumber:           // ??
                //                    case UnicodeCategory.OtherNumber:            // ??
                case UnicodeCategory.NonSpacingMark:
                //                    case UnicodeCategory.SpacingCombiningMark:   // Mc
                case UnicodeCategory.ConnectorPunctuation:       // Pc
                    validChars.Add(c);
                    break;

                default:
                    invalidChars.Add(c);
                    break;
                }
            }

            // \w - we will create strings from valid characters that form \w and make sure that the regex engine catches this.
            // Build a random string with valid characters followed by invalid characters
            Random random = new Random(-55);
            Regex  regex  = new Regex(@"\w*");

            int validCharLength   = 10;
            int invalidCharLength = 15;

            for (int i = 0; i < 100; i++)
            {
                var builder1 = new StringBuilder();
                var builder2 = new StringBuilder();

                for (int j = 0; j < validCharLength; j++)
                {
                    char c = validChars[random.Next(validChars.Count)];
                    builder1.Append(c);
                    builder2.Append(c);
                }

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                string input = builder1.ToString();
                Match  match = regex.Match(input);
                Assert.True(match.Success);

                Assert.Equal(builder2.ToString(), match.Value);
                Assert.Equal(0, match.Index);
                Assert.Equal(validCharLength, match.Length);

                match = match.NextMatch();
                do
                {
                    // We get empty matches for each of the non-matching characters of input to match
                    // the * wildcard in regex pattern.
                    Assert.Equal(string.Empty, match.Value);
                    Assert.Equal(0, match.Length);
                    match = match.NextMatch();
                } while (match.Success);
            }

            // Build a random string with invalid characters followed by valid characters and then again invalid
            random = new Random(-55);
            regex  = new Regex(@"\w+");

            validCharLength   = 10;
            invalidCharLength = 15;

            for (int i = 0; i < 500; i++)
            {
                var builder1 = new StringBuilder();
                var builder2 = new StringBuilder();

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                for (int j = 0; j < validCharLength; j++)
                {
                    char c = validChars[random.Next(validChars.Count)];
                    builder1.Append(c);
                    builder2.Append(c);
                }

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                string input = builder1.ToString();

                Match match = regex.Match(input);
                Assert.True(match.Success);

                Assert.Equal(builder2.ToString(), match.Value);
                Assert.Equal(invalidCharLength, match.Index);
                Assert.Equal(validCharLength, match.Length);

                match = match.NextMatch();
                Assert.False(match.Success);
            }

            validChars   = new List <char>();
            invalidChars = new List <char>();
            for (int i = 0; i < MaxUnicodeRange; i++)
            {
                char c = (char)i;
                if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber)
                {
                    validChars.Add(c);
                }
                else
                {
                    invalidChars.Add(c);
                }
            }

            // \d - we will create strings from valid characters that form \d and make sure that the regex engine catches this.
            // Build a random string with valid characters and then again invalid
            regex = new Regex(@"\d+");

            validCharLength   = 10;
            invalidCharLength = 15;

            for (int i = 0; i < 100; i++)
            {
                var builder1 = new StringBuilder();
                var builder2 = new StringBuilder();

                for (int j = 0; j < validCharLength; j++)
                {
                    char c = validChars[random.Next(validChars.Count)];
                    builder1.Append(c);
                    builder2.Append(c);
                }

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                string input = builder1.ToString();
                Match  match = regex.Match(input);


                Assert.Equal(builder2.ToString(), match.Value);
                Assert.Equal(0, match.Index);
                Assert.Equal(validCharLength, match.Length);

                match = match.NextMatch();
                Assert.False(match.Success);
            }

            // Build a random string with invalid characters, valid and then again invalid
            regex = new Regex(@"\d+");

            validCharLength   = 10;
            invalidCharLength = 15;

            for (int i = 0; i < 100; i++)
            {
                var builder1 = new StringBuilder();
                var builder2 = new StringBuilder();

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                for (int j = 0; j < validCharLength; j++)
                {
                    char c = validChars[random.Next(validChars.Count)];
                    builder1.Append(c);
                    builder2.Append(c);
                }

                for (int j = 0; j < invalidCharLength; j++)
                {
                    builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
                }

                string input = builder1.ToString();

                Match match = regex.Match(input);
                Assert.True(match.Success);

                Assert.Equal(builder2.ToString(), match.Value);
                Assert.Equal(invalidCharLength, match.Index);
                Assert.Equal(validCharLength, match.Length);

                match = match.NextMatch();
                Assert.False(match.Success);
            }
        }
        private static IEnumerable<string> GetMatches(Match match)
        {
            var dependencies = new List<string>();
            while (match.Success)
            {
                var path = match.Groups["path"].Value;
                dependencies.Add(path);

                match = match.NextMatch();
            }
            return dependencies;
        }
예제 #31
0
        public int probe(string userId)
        {
            form1.setLogT("probe " + userId + "..");

            string respHtml = Form1.weLoveYue(
                form1,
                //         "https://www.facebook.com/" + userId + "?v=friends",
                "https://www.facebook.com/" + userId + "/friends",
                "GET", "", false, "");

            if (respHtml.Equals("wrong address"))
            {
                form1.setLogtRed("用户id错误");
                return -2;
            }

            if (
                respHtml.Equals("Found")
                ||
                (respHtml.Length < 100000 && respHtml.Contains("class=\"uiHeaderTitle\">Favorites</h4>"))
                ||
                (respHtml.Length < 100000 && respHtml.Contains("Please enter the text below"))
                )
            {
                form1.setLogT("session expired!");
                return -1;
            }

            if (respHtml.Length < 200001)
            {
                form1.setLogtRed("无权限访问该用户好友列表");
                return -2;
            }

            rgx = @"(?<=""USER_ID"":"")\d+?(?="")";
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (myMatch.Success)
            {
                user_id = myMatch.Groups[0].Value;
            }

            rgx = @"(?<=\[\]\,{""revision"":)\d+?(?=\,)";
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (myMatch.Success)
            {
                revision = myMatch.Groups[0].Value;
            }

            respHtml = respHtml.Substring(60000, respHtml.Length - 60000);
            rgx = @"(?<=friends_all"" aria-controls=""pagelet_timeline_app_collection_).*?(?="")";
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (myMatch.Success)
            {
                collection_token = myMatch.Groups[0].Value;
            }
            collection_token = Form1.ToUrlEncode(collection_token);

            rgx = @"^\d+(?=\%)";
            myMatch = (new Regex(rgx)).Match(collection_token);
            if (myMatch.Success)
            {
                profile_id = myMatch.Groups[0].Value;
            }

            respHtml = respHtml.Substring(140000, respHtml.Length - 140000);
            rgx = @"(?<=https:\/\/www\.facebook\.com\/)(\w|\.)+?(?=\?fref=pb&amp;hc_location=\w+?"" tabindex=)";
            myMatch = (new Regex(rgx)).Match(respHtml);
            while (myMatch.Success)
            {
                //ignore all digital id
                Regex rex = new Regex(@"^(\.|\d)+$");
                if (rex.IsMatch(myMatch.Groups[0].Value))
                {
                    continue;
                }
                if ((gFriends.Count == 0) || (!gFriends.Contains(myMatch.Groups[0].Value)))
                {
                    gFriends.Add(myMatch.Groups[0].Value);
                    string pattern = @"^";
                    string replacement = "1-1-";
                    writeResult(Regex.Replace(myMatch.Groups[0].Value, pattern, replacement) + Environment.NewLine);
                    successInOneProbe++;
                }
                myMatch = myMatch.NextMatch();
            }

            rgx = @"(?<=pagelet_timeline_app_collection_" + collection_token.Replace("%3a", ":") + @""",{""__m"":""\w+_\w+_\w+""},"").*?(?="")";
            myMatch = (new Regex(rgx)).Match(respHtml);
            if (myMatch.Success)
            {
                cursor = myMatch.Groups[0].Value;
            }
            else //just on one page
            {
                return 1;
            }
            cursor = Form1.ToUrlEncode(cursor);

            //page by page
            while (true)
            {
                if (Form1.gForceToStop)
                {
                    break;
                }
                respHtml = Form1.weLoveYue(
                    form1,
                    "https://www.facebook.com/ajax/pagelet/generic.php/AllFriendsAppCollectionPagelet?data=%7B%22collection_token%22%3A%22"
                    + collection_token + "%22%2C%22cursor%22%3A%22" + cursor + "%22%2C%22tab_key%22%3A%22friends%22%2C%22profile_id%22%3A"
                    + profile_id + "%2C%22overview%22%3Afalse%2C%22ftid%22%3Anull%2C%22order%22%3Anull%2C%22sk%22%3A%22friends%22%2C%22importer_state%22%3Anull%7D&__user="******"&__a=1&__dyn=7AmajEyl2qm2d2u6aEB191qeCwKyWgyi8zQC-K26m6oKezob4q68K5Uc-dy88axbxjx27W88ybx-qCEWfybDGcCxC2e78"
                    + "&__req=g&__rev=" + revision
                    ,
                    "GET", "", false, "");

                //rgx = @"(?<=https:\/\/www\.facebook\.com\/)(\w|\.)+?(?=\?fref=pb&amp;hc_location=\w+?"" tabindex=)";
                rgx = @"(?<=facebook\.com\\\/)(\w|\.)+?(?=\?fref=pb\&amp\;hc_location=\w+?\\\"" tabindex=)";

                myMatch = (new Regex(rgx)).Match(respHtml);
                while (myMatch.Success)
                {
                    //ignore all digital id
                    Regex rex = new Regex(@"^(\.|\d)+$");
                    if (rex.IsMatch(myMatch.Groups[0].Value))
                    {
                        continue;
                    }
                    if ((gFriends.Count == 0) || (!gFriends.Contains(myMatch.Groups[0].Value)))
                    {
                        gFriends.Add(myMatch.Groups[0].Value);
                        string pattern = @"^";
                        string replacement = "1-1-";
                        writeResult(Regex.Replace(myMatch.Groups[0].Value, pattern, replacement) + Environment.NewLine);
                        successInOneProbe++;
                    }
                    myMatch = myMatch.NextMatch();
                }

                rgx = @"(?<=pagelet_timeline_app_collection_" + collection_token.Replace("%3a", ":") + @""",{""__m"":""\w+_\w+_\w+""},"").*?(?="")";
                myMatch = (new Regex(rgx)).Match(respHtml);
                if (myMatch.Success)
                {
                    cursor = myMatch.Groups[0].Value;
                }
                else //to the end of friends list
                {
                    return 1;
                }
                cursor = Form1.ToUrlEncode(cursor);
            }
            return 1;
        }
예제 #32
0
        public void showNextAppTime()
        {
            string county = form1.selecteCounty.Shops[form1.selectedShop];        //big surprise!!! the official entrance is the encoding with s-jis of county's name, BUT, shop's name also works! And now I use shop's name with others' will narely do

            string shop = form1.selecteCounty.Sids[form1.selectedShop];
            string forTest = Form1.ToUrlEncode(
                        county,
                        System.Text.Encoding.GetEncoding("shift-jis")
                     );

            DateTime dateTime = DateTime.MinValue;
            string day = "";
            string time = "";

            string html = Form1.weLoveYue(
                form1,
                "http://aksale.advs.jp/cp/akachan_sale_pc/search_event_list.cgi?area2="
                + Form1.ToUrlEncode(
                        county,
                        System.Text.Encoding.GetEncoding("shift-jis")
                     )
                + "&event_type=" + sizeType + "&sid=" + shop + "&kmws=",

                "GET", "", false, "", ref  cookieContainer,
                false
                );

            //available
            //   <th>予約受付期間</th>
            //					<td>
            //						10/12<font color="#ff0000">(月)</font>&nbsp;13:30~10/12<font color="#ff0000">(月)</font>&nbsp;22:00<br />

            if (county == form1.selecteCounty.Shops[form1.selectedShop]
                && shop == form1.selecteCounty.Sids[form1.selectedShop]
                && sizeType == form1.selectedType)
            {
                rgx = @"(?<=<th>予約受付期間</th>\n.*\n\s*)\d+\/\d+(?=\D)";
                myMatch = (new Regex(rgx)).Match(html);
                while (myMatch.Success)
                {
                    day = myMatch.Groups[0].Value;// no available appointment
                    rgx = @"(?<=<th>予約受付期間</th>\n.*\n\s*" + day + @"(\s|\S)+?)\d+\:\d+(?=\D)";
                    Match match2 = (new Regex(rgx)).Match(html);
                    if (match2.Success)
                    {
                        time = match2.Groups[0].Value;

                        DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
                        dtFormat.ShortDatePattern = "yyyy-M-d hh:mm:ss";
                        dateTime = Convert.ToDateTime("2015-" + Regex.Match(day, @"\d+(?=\/)") + "-" + Regex.Match(day, @"(?<=\/)\d+") + " " + time + ":00");

                        //how to find the year ?

                        TimeZoneInfo jst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
                        TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
                        DateTime nowInTokyoTime = TimeZoneInfo.ConvertTime(DateTime.Now, jst);
                        if ((dateTime - nowInTokyoTime).TotalMinutes > -15)
                        {
                            delegate2 d111 = new delegate2(
                                delegate() {
                                    form1.label14.Text = "the nearest booking on type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county
                                    + " is on: \n" + dateTime.ToString("MM/dd HH:mm") + " Tokyo Standard Time\n"
                                    + TimeZoneInfo.ConvertTimeFromUtc(TimeZoneInfo.ConvertTimeToUtc(dateTime, jst), cst).ToString("MM/dd HH:mm")
                                    + " China Standard Time"
                                    ;
                                 }
                            );
                            form1.label14.Invoke(d111);
                            return;
                        }
                    }
                    myMatch = myMatch.NextMatch();
                }
                delegate2 d222 = new delegate2(
                    delegate() {
                        if (Regex.Match(html, @"条件に一致する予約販売が存在しません").Success)
                        {
                            form1.label14.Text = "There is no type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county;
                        }
                        else
                        {
                            form1.label14.Text = "No available booking these days on type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county;
                        }
                    }
                );
                form1.label14.Invoke(d222);
            }//end of if the search option not changed
        }
예제 #33
0
 public DetailRegexMatches(string input, Match match)
 {
     this.input = input;
     this.found = false;
     List<DetailRegexMatch> matchList = new List<DetailRegexMatch>();
     while (match.Success)
     {
         this.found = true;
         DetailRegexMatch regexMatch = new DetailRegexMatch();
         regexMatch.indexMatch = match.Index;
         regexMatch.lengthMatch = match.Length;
         regexMatch.value = match.Value;
         List<DetailRegexGroup> groupList = new List<DetailRegexGroup>();
         foreach (Group group in match.Groups)
         {
             DetailRegexGroup regexGroup = new DetailRegexGroup();
             regexGroup.indexMatch = group.Index;
             regexGroup.lengthMatch = group.Length;
             regexGroup.value = group.Value;
             List<DetailRegexCapture> captureList = new List<DetailRegexCapture>();
             foreach (Capture capture in group.Captures)
             {
                 DetailRegexCapture regexCapture = new DetailRegexCapture();
                 regexCapture.indexMatch = capture.Index;
                 regexCapture.lengthMatch = capture.Length;
                 regexCapture.value = capture.Value;
                 captureList.Add(regexCapture);
             }
             regexGroup.captures = captureList.ToArray();
             groupList.Add(regexGroup);
         }
         regexMatch.groups = groupList.ToArray();
         matchList.Add(regexMatch);
         match = match.NextMatch();
     }
     matches = matchList.ToArray();
 }
 private string UpdateAssemblyFile(ISourceControl sourceControl, VersionPart versionPart, Match match,
     string fileAssemblySetting, string newFile, ref bool isCheckout)
 {
     if (match.Success)
     {
         if (!isCheckout)
         {
             sourceControl.Checkout(fileAssemblySetting);
             isCheckout = true;
         }
         do
         {
             var group = match.Groups[((int) versionPart) + 1];
             int value = int.Parse(@group.Value);
             newFile = newFile.Substring(0, @group.Index) + (value + 1) + newFile.Substring(@group.Index + @group.Length);
             match = match.NextMatch();
         } while (match.Success);
     }
     return newFile;
 }
 protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match)
 {
     try
     {
             if (!match.Success) return NextInstruction.Skip;
             var datetime = false;
             while (match.Success)
             {
                 if (!datetime) context.FieldBuffer[context.SourceHeaderInfo["Datetime"]] = match.Groups["Datetime"].Value;
                 datetime = true;
                 if (context.SourceHeaderInfo.ContainsKey(match.Groups[1].Value))
                     context.FieldBuffer[context.SourceHeaderInfo[match.Groups[1].Value]] = match.Groups[2].Value;
                 match = match.NextMatch();
             }
             context.FieldBuffer[context.SourceHeaderInfo["Description"]] = source;
         return NextInstruction.Return;
     }
     catch (Exception e)
     {
         Console.WriteLine("Error while processing veribranch record: " + e);
         return NextInstruction.Abort;
     }
 }
        private void fun1()
        {
            DateTime dt   = Convert.ToDateTime(dateEdit1.EditValue.ToString());
            string   date = dt.ToString("yyyyMMdd");

            Workbook tem_workbook = new Workbook();

            tem_workbook.LoadDocument(forecastCodeFile);

            Range range = tem_workbook.Worksheets[0].GetUsedRange();

            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            Stream        stream   = null;
            string        str_json = null;
            List <string> list     = new List <string>();

            string[] itemStrs = null;

            for (int i = 1; i < range.RowCount; i++)
            {
                try
                {
                    string vv = SetAddress(date, tem_workbook.Worksheets[0][i, 1].Value.ToString(), dataType);
                    stream = client.OpenRead(vv);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(tem_workbook.Worksheets[0][i, 1].Value.ToString() + "," + tem_workbook.Worksheets[0][i, 2].Value.ToString());
                    MessageBox.Show("操作超时,当前工作将自动退出。请在稳定的网络环境下执行此任务!");

                    continue;

                    if (thread.ThreadState == System.Threading.ThreadState.Running)
                    {
                        thread.Abort();
                    }
                    this.Close();
                }



                str_json = new StreamReader(stream).ReadToEnd();

                if (str_json != "")
                {
                    try
                    {
                        //MessageBox.Show(str_json);
                        Regex regexObj = new Regex(@"\[(?<result>)[^[\]]+\]");
                        System.Text.RegularExpressions.Match matchResult = regexObj.Match(str_json);
                        int tempRow = 1;
                        while (matchResult.Success)
                        {
                            string s1 = matchResult.Groups[0].Value.Replace("[", "").Replace("]", "");
                            //MessageBox.Show(string.Format("i:{0}, {1}", i, s1));
                            itemStrs = s1.Split(',');

                            if (target_datatype == "全部")
                            {
                                worksheet[10 * (i - 1) + tempRow, 0].SetValue(10 * (i - 1));
                                worksheet[10 * (i - 1) + tempRow, 1].SetValue(dataType);
                                worksheet[10 * (i - 1) + tempRow, 2].SetValue(tem_workbook.Worksheets[0][i, 2].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 3].SetValue(date);

                                worksheet[10 * (i - 1) + tempRow, 4].SetValue(itemStrs[0].Replace("\"", ""));
                                worksheet[10 * (i - 1) + tempRow, 5].SetValue(itemStrs[1]);
                                worksheet[10 * (i - 1) + tempRow, 6].SetValue(itemStrs[2]);
                                worksheet[10 * (i - 1) + tempRow, 7].SetValue(itemStrs[3]);
                                worksheet[10 * (i - 1) + tempRow, 8].SetValue(itemStrs[4]);
                                worksheet[10 * (i - 1) + tempRow, 9].SetValue(DateTime.Now);

                                worksheet[10 * (i - 1) + tempRow, 10].SetValue(tem_workbook.Worksheets[0][i, 4].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 11].SetValue(tem_workbook.Worksheets[0][i, 5].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 12].SetValue(tem_workbook.Worksheets[0][i, 1].Value.ToString());
                            }
                            if (target_datatype == "飞机")
                            {
                                worksheet[10 * (i - 1) + tempRow, 0].SetValue(10 * (i - 1));
                                worksheet[10 * (i - 1) + tempRow, 1].SetValue(dataType);
                                worksheet[10 * (i - 1) + tempRow, 2].SetValue(tem_workbook.Worksheets[0][i, 2].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 3].SetValue(date);

                                worksheet[10 * (i - 1) + tempRow, 4].SetValue(itemStrs[0].Replace("\"", ""));
                                worksheet[10 * (i - 1) + tempRow, 5].SetValue(itemStrs[1]);
                                worksheet[10 * (i - 1) + tempRow, 6].SetValue(itemStrs[2]);

                                worksheet[10 * (i - 1) + tempRow, 7].SetValue(DateTime.Now);

                                worksheet[10 * (i - 1) + tempRow, 8].SetValue(tem_workbook.Worksheets[0][i, 4].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 9].SetValue(tem_workbook.Worksheets[0][i, 5].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 10].SetValue(tem_workbook.Worksheets[0][i, 1].Value.ToString());
                            }
                            if (target_datatype == "火车")
                            {
                                worksheet[10 * (i - 1) + tempRow, 0].SetValue(10 * (i - 1));
                                worksheet[10 * (i - 1) + tempRow, 1].SetValue(dataType);
                                worksheet[10 * (i - 1) + tempRow, 2].SetValue(tem_workbook.Worksheets[0][i, 2].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 3].SetValue(date);

                                worksheet[10 * (i - 1) + tempRow, 4].SetValue(itemStrs[0].Replace("\"", ""));
                                worksheet[10 * (i - 1) + tempRow, 5].SetValue(itemStrs[1]);
                                worksheet[10 * (i - 1) + tempRow, 6].SetValue(itemStrs[2]);

                                worksheet[10 * (i - 1) + tempRow, 7].SetValue(DateTime.Now);

                                worksheet[10 * (i - 1) + tempRow, 8].SetValue(tem_workbook.Worksheets[0][i, 4].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 9].SetValue(tem_workbook.Worksheets[0][i, 5].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 10].SetValue(tem_workbook.Worksheets[0][i, 1].Value.ToString());
                            }
                            if (target_datatype == "汽车")
                            {
                                worksheet[10 * (i - 1) + tempRow, 0].SetValue(10 * (i - 1));
                                worksheet[10 * (i - 1) + tempRow, 1].SetValue(dataType);
                                worksheet[10 * (i - 1) + tempRow, 2].SetValue(tem_workbook.Worksheets[0][i, 2].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 3].SetValue(date);

                                worksheet[10 * (i - 1) + tempRow, 4].SetValue(itemStrs[0].Replace("\"", ""));
                                worksheet[10 * (i - 1) + tempRow, 5].SetValue(itemStrs[1]);
                                worksheet[10 * (i - 1) + tempRow, 6].SetValue(itemStrs[2]);

                                worksheet[10 * (i - 1) + tempRow, 7].SetValue(DateTime.Now);

                                worksheet[10 * (i - 1) + tempRow, 8].SetValue(tem_workbook.Worksheets[0][i, 4].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 9].SetValue(tem_workbook.Worksheets[0][i, 5].Value.ToString());
                                worksheet[10 * (i - 1) + tempRow, 10].SetValue(tem_workbook.Worksheets[0][i, 1].Value.ToString());
                            }

                            matchResult = matchResult.NextMatch();

                            tempRow++;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                sum++;
                RunWithInoke(sum);
            }

            taskExecuted = true;
            workbook.SaveDocument(docPath);



            XtraMessageBox.Show("所有数据已经采集完成!");
        }
        protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match)
        {
            if (!match.Success) return NextInstruction.Skip;
            var groupCollection = match.Groups;

            foreach (var key in RegSplitForAll.GetGroupNames())
            {
                int tmp;
                if (int.TryParse(key, out tmp)) continue;
                if (!context.SourceHeaderInfo.ContainsKey(key)) continue;
                if (groupCollection[key].Value.Length > 0)
                    context.FieldBuffer[context.SourceHeaderInfo[key]] = groupCollection[key].Value;
            }

            match = match.NextMatch();

            while (match.Success)
            {
                if (context.SourceHeaderInfo.ContainsKey(match.Groups["x"].Value))
                    context.FieldBuffer[context.SourceHeaderInfo[match.Groups["x"].Value]] = match.Groups["y"].Value;
                match = match.NextMatch();
            }

            context.FieldBuffer[context.SourceHeaderInfo["Description"]] = source;
            return NextInstruction.Return;
        }
예제 #38
0
        // Three very similar algorithms appear below: replace (pattern),
        // replace (evaluator), and split.

        /// <summary>
        /// Replaces all occurrences of the regex in the string with the
        /// replacement pattern.
        ///
        /// Note that the special case of no matches is handled on its own:
        /// with no matches, the input string is returned unchanged.
        /// The right-to-left case is split out because StringBuilder
        /// doesn't handle right-to-left string building directly very well.
        /// </summary>
        public string Replace(Regex regex, string input, int count, int startat)
        {
            if (count < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
            }
            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
            }

            if (count == 0)
            {
                return(input);
            }

            Match match = regex.Match(input, startat);

            if (!match.Success)
            {
                return(input);
            }
            else
            {
                Span <char> charInitSpan = stackalloc char[256];
                var         vsb          = new ValueStringBuilder(charInitSpan);

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    do
                    {
                        if (match.Index != prevat)
                        {
                            vsb.Append(input.AsSpan(prevat, match.Index - prevat));
                        }

                        prevat = match.Index + match.Length;
                        ReplacementImpl(ref vsb, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat < input.Length)
                    {
                        vsb.Append(input.AsSpan(prevat, input.Length - prevat));
                    }
                }
                else
                {
                    // In right to left mode append all the inputs in reversed order to avoid an extra dynamic data structure
                    // and to be able to work with Spans. A final reverse of the transformed reversed input string generates
                    // the desired output. Similar to Tower of Hanoi.

                    int prevat = input.Length;

                    do
                    {
                        if (match.Index + match.Length != prevat)
                        {
                            vsb.AppendReversed(input.AsSpan(match.Index + match.Length, prevat - match.Index - match.Length));
                        }

                        prevat = match.Index;
                        ReplacementImplRTL(ref vsb, match);
                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat > 0)
                    {
                        vsb.AppendReversed(input.AsSpan(0, prevat));
                    }

                    vsb.Reverse();
                }

                return(vsb.ToString());
            }
        }
예제 #39
0
		/// <summary>
		/// Goes through <paramref name="m"/> matches and fill <paramref name="matches"/> array with results
		/// according to Pattern Order.
		/// </summary>
		/// <param name="r"><see cref="Regex"/> that produced the match</param>
		/// <param name="m"><see cref="Match"/> to iterate through all matches by NextMatch() call.</param>
		/// <param name="matches">Array for storing results.</param>
		/// <param name="addOffsets">Whether or not add arrays with offsets instead of strings.</param>
		/// <returns>Number of full pattern matches.</returns>
		private static int FillMatchesArrayAllPatternOrder(Regex r, Match m, ref PhpArray matches, bool addOffsets)
		{
			// second index, increases at each match in pattern order
			int j = 0;
			while (m.Success)
			{
				// add all groups
				for (int i = 0; i < m.Groups.Count; i++)
				{
					object arr = NewArrayItem(m.Groups[i].Value, m.Groups[i].Index, addOffsets);

                    AddGroupNameToResult(r, matches, i, (ms, groupName) =>
                    {
                        if (j == 0) ms[groupName] = new PhpArray();
                        ((PhpArray)ms[groupName])[j] = arr;
                    });

					if (j == 0) matches[i] = new PhpArray();
					((PhpArray)matches[i])[j] = arr;
				}

				j++;
				m = m.NextMatch();
			}

			return j;
		}
예제 #40
0
        private static IEnumerable<Match> EnumerateMatchesRightToLeft(Match match, int count)
        {
            var matches = new List<Match>();

            while (match.Success)
            {
                matches.Add(match);

                count--;

                if (count == 0)
                    break;

                match = match.NextMatch();
            }

            for (int i = matches.Count - 1; i >= 0; i--)
                yield return matches[i];
        }
예제 #41
0
        /// <summary>
        /// Does a split. In the right-to-left case we reorder the
        /// array to be forwards.
        /// </summary>
        private static string[] Split(Regex regex, string input, int count, int startat)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
            }
            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
            }

            string[] result;

            if (count == 1)
            {
                result    = new string[1];
                result[0] = input;
                return(result);
            }

            count -= 1;

            Match match = regex.Match(input, startat);

            if (!match.Success)
            {
                result    = new string[1];
                result[0] = input;
                return(result);
            }
            else
            {
                List <string> al = new List <string>();

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    while (true)
                    {
                        al.Add(input.Substring(prevat, match.Index - prevat));

                        prevat = match.Index + match.Length;

                        // add all matched capture groups to the list.
                        for (int i = 1; i < match.Groups.Count; i++)
                        {
                            if (match.IsMatched(i))
                            {
                                al.Add(match.Groups[i].ToString());
                            }
                        }

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();

                        if (!match.Success)
                        {
                            break;
                        }
                    }

                    al.Add(input.Substring(prevat, input.Length - prevat));
                }
                else
                {
                    int prevat = input.Length;

                    while (true)
                    {
                        al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));

                        prevat = match.Index;

                        // add all matched capture groups to the list.
                        for (int i = 1; i < match.Groups.Count; i++)
                        {
                            if (match.IsMatched(i))
                            {
                                al.Add(match.Groups[i].ToString());
                            }
                        }

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();

                        if (!match.Success)
                        {
                            break;
                        }
                    }

                    al.Add(input.Substring(0, prevat));

                    al.Reverse(0, al.Count);
                }

                return(al.ToArray());
            }
        }
 protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match)
 {
     while (match.Success)
     {
         if (context.SourceHeaderInfo.ContainsKey(match.Groups[1].Value))
             context.FieldBuffer[context.SourceHeaderInfo[match.Groups[1].Value]] = match.Groups[2].Value;
         match = match.NextMatch();
     }
     return NextInstruction.Return;
 }
예제 #43
0
        private void ReadVHDL()
        {
            int iMod = Signal.Modes.Inout;
            matchEnts = regexEnts.Match(content);
            while (matchEnts.Success)
            {
                if (matchEnts.Groups[1].Value.ToString() == CBEntity.SelectedItem.ToString())
                {
                    Match matchMods = regexMods.Match(matchEnts.Value);
                    while (matchMods.Success)
                    {
                        Match matchSigs = regexSigs.Match(matchMods.Value);
                        while (matchSigs.Success)
                        {

                            if (matchMods.Groups[3].Value == "in ")
                            {
                                iMod = Signal.Modes.In;
                            }
                            if (matchMods.Groups[3].Value == "out ")
                            {
                                iMod = Signal.Modes.Out;
                            }
                            if (matchMods.Groups[3].Value == "inout ")
                            {
                                iMod = Signal.Modes.Inout;
                            }
                            if ((matchSigs.Groups[1].Value != "in") && (matchSigs.Groups[1].Value != "out") && (matchSigs.Groups[1].Value != "inout"))
                                TempSignals.Add(new Signal(matchSigs.Groups[1].Value, iMod));

                            matchSigs = matchSigs.NextMatch();
                        }

                        matchMods = matchMods.NextMatch();
                    }
                }
                matchEnts = matchEnts.NextMatch();
            }
        }
예제 #44
0
        private void button1_Click(object sender, EventArgs e)
        {
            string pattern = @"^";
            string replacement = "1-1-";
            string result = Regex.Replace("12345", pattern, replacement);
            setLogT(result);

            rgx = @"(?<=aa).*?(?=aa)";
            myMatch = (new Regex(rgx)).Match("qqqqqaaqwdsfaafferaafe222aa2222444aa444444222faaloveaa");
            while (myMatch.Success)
            {
                setLogT(myMatch.Groups[0].Value);
                myMatch = myMatch.NextMatch();
            }

            string message = "4344.34334.23.24.";
            Regex rex = new Regex(@"^(\.|\d)+$");
            if (rex.IsMatch(message))
            {
                //float result2 = float.Parse(message);
                setLogT("match");
            }
            else
                setLogT("not match");

            int aa;
            if ((aa = 4) == 4)
            {
                setLogT(aa.ToString());
            }
        }
예제 #45
0
파일: BaseMachine.cs 프로젝트: mdae/MonoRT
        virtual public string [] Split(Regex regex, string input, int count, int startat)
        {
            ArrayList splits = new ArrayList();

            if (count == 0)
            {
                count = Int32.MaxValue;
            }

            int   ptr = startat;
            Match m   = null;

            while (--count > 0)
            {
                if (m != null)
                {
                    m = m.NextMatch();
                }
                else
                {
                    m = regex.Match(input, ptr);
                }

                if (!m.Success)
                {
                    break;
                }

                if (regex.RightToLeft)
                {
                    splits.Add(input.Substring(m.Index + m.Length, ptr - m.Index - m.Length));
                }
                else
                {
                    splits.Add(input.Substring(ptr, m.Index - ptr));
                }

                int gcount = m.Groups.Count;
                for (int gindex = 1; gindex < gcount; gindex++)
                {
                    Group grp = m.Groups [gindex];
                    splits.Add(input.Substring(grp.Index, grp.Length));
                }

                if (regex.RightToLeft)
                {
                    ptr = m.Index;
                }
                else
                {
                    ptr = m.Index + m.Length;
                }
            }

            if (regex.RightToLeft && ptr >= 0)
            {
                splits.Add(input.Substring(0, ptr));
            }
            if (!regex.RightToLeft && ptr <= input.Length)
            {
                splits.Add(input.Substring(ptr));
            }

            return((string [])splits.ToArray(typeof(string)));
        }
예제 #46
0
        /// <summary>
        /// Parses the header.
        /// </summary>
        /// <param name="header">The header.</param>
        public static void ParseHeader(ref Header header)
        {
#if !PocketPC
            string hdr = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(header.OriginalData, 0, header.OriginalData.Length);
#else
            string hdr = Pop3Client.PPCEncode.GetString(header.OriginalData, 0, header.OriginalData.Length);
#endif
            hdr = System.Text.RegularExpressions.Regex.Match(hdr, @"[\s\S]+?((?=\r?\n\r?\n)|\Z)").Value;
            hdr = Parser.Unfold(hdr);
            //hdr = hdr);
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(hdr, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");
            while (m.Success)
            {
                string name  = FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':')));
                string value = Codec.RFC2047Decode(m.Value.Substring(m.Value.IndexOf(":") + 1)).Trim('\r', '\n').TrimStart(' ');
                if (name.Equals("received"))
                {
                    header.Trace.Add(Parser.ParseTrace(m.Value.Trim(' ')));
                }
                else if (name.Equals("to"))
                {
                    header.To = Parser.ParseAddresses(value);
                }
                else if (name.Equals("cc"))
                {
                    header.Cc = Parser.ParseAddresses(value);
                }
                else if (name.Equals("bcc"))
                {
                    header.Bcc = Parser.ParseAddresses(value);
                }
                else if (name.Equals("reply-to"))
                {
                    header.ReplyTo = Parser.ParseAddress(value);
                }
                else if (name.Equals("from"))
                {
                    header.From = Parser.ParseAddress(value);
                }
                else if (name.Equals("sender"))
                {
                    header.Sender = Parser.ParseAddress(value);
                }
                else if (name.Equals("content-type"))
                {
                    header.ContentType = Parser.GetContentType(m.Value);
                }
                else if (name.Equals("content-disposition"))
                {
                    header.ContentDisposition = Parser.GetContentDisposition(m.Value);
                }
                //else
                //{
                header.HeaderFields.Add(name, value);
                header.HeaderFieldNames.Add(name, m.Value.Substring(0, m.Value.IndexOf(':')));
                //}
                m = m.NextMatch();

                if (HeaderFieldParsing != null)
                {
                    HeaderFieldParsing(null, header);
                }
            }
        }
예제 #47
0
파일: Form1.cs 프로젝트: daiyyr/yueavac
        public int apply2(int threadNo)
        {
            if (urlForStep2[threadNo] == "Appointment Letter")
            {
                return -12;
            }

            setLogT(threadNo, "step2");
            gTicket[threadNo] = 1;

            string p = "";
            reg = @"(?<=aspx\?P=)(\s|\S)+?(?=$)";
            myMatch = (new Regex(reg)).Match(urlForStep2[threadNo]);
            if (myMatch.Success)
            {
                p = ToUrlEncode(myMatch.Groups[0].Value);
            }
            else
            {
                setLogtRed(threadNo, "invalid URL for step2, 申请异常终止!");
                return -2;
            }

            setLogT(threadNo, "getting step2 page..");
            gettingstep2page:
            string respHtml = weLoveYue(
                threadNo,
                urlForStep2[threadNo],
                "GET",
                "",
                true,
                "");

            reg = @"(?<=name=""__EVENTVALIDATION"" id=""__EVENTVALIDATION"" value="").*?(?="" />)";
            myMatch = (new Regex(reg)).Match(respHtml);
            if (myMatch.Success)
            {
                gEventvalidation[threadNo] = ToUrlEncode(myMatch.Groups[0].Value);
            }
            else
            {
                if (gForceToStop)
                {
                    return -4;
                }
                setLogtRed(threadNo, "getting page failed, retry..");
                goto gettingstep2page;
            }

            reg = @"(?<=id=""__VIEWSTATE"" value="").*?(?="" />)";
            myMatch = (new Regex(reg)).Match(respHtml);
            if (myMatch.Success)
            {
                gViewstate[threadNo] = ToUrlEncode(myMatch.Groups[0].Value);
            }
            else
            {
                if (gForceToStop)
                {
                    return -4;
                }
                setLogtRed(threadNo, "getting page failed, retry..");
                goto gettingstep2page;
            }

            setLogT(threadNo, "filling in details..");

            verification1:
            ThreadStart starter = delegate { showVerificationCode(respHtml, threadNo); };
            new Thread(starter).Start();

            while (gVerificationCode[threadNo] == null || gVerificationCode[threadNo] == "")
            {
                Thread.Sleep(50);
            }
            details:
            respHtml = weLoveYue(
                threadNo,
                "https://www.visaservices.in/DIAC-China-Appointment_new/AppScheduling/AppSchedulingVisaCategory.aspx?p="+p,
                "POST",
                urlForStep2[threadNo],
                true,
                "__VIEWSTATE=" + gViewstate[threadNo]
                + "&ctl00%24plhMain%24repAppVisaDetails%24ctl01%24tbxPassportNo="
                + gPassport
                + "&ctl00%24plhMain%24repAppVisaDetails%24ctl01%24cboTitle="
                + gTitle
                + "&ctl00%24plhMain%24repAppVisaDetails%24ctl01%24tbxFName="
                + gFirstName
                + "&ctl00%24plhMain"
                + "%24repAppVisaDetails%24ctl01%24tbxLName="
                + gLastName
                + "&ctl00%24plhMain%24repAppVisaDetails%24ctl01%24tbxSTDCode="
                + gSTDCode
                + "&ctl00%24plhMain%24repAppVisaDetails%24ctl01%24tbxContactNumber="
                + gContactNumber
                + "&ctl00%24plhMain%24repAppVisaDetails"
                + "%24ctl01%24tbxMobileNumber="
                + gMobile
                + "&ctl00%24plhMain%24btnSubmit=Submit"
                + "&ctl00%24plhMain%24hdnValidation1=Please+enter+Passport+No.+of+Applicant+no.&ctl00%24plhMain%24hdnValidation2"
                + "=Please+select+title+for+applicant+no.&ctl00%24plhMain%24hdnValidation3=Please+enter+given+name%28s%29"
                + "+of+Applicant+no.&ctl00%24plhMain%24hdnValidation4=Please+enter+surname+of+Applicant+no.&ctl00%24plhMain"
                + "%24hdnValidation5=Please+enter+mobile+no.+for+applicant+no.&ctl00%24plhMain%24hdnValidation6=Please+enter"
                + "+valid+Area+Code+for+applicant+no.&ctl00%24plhMain%24hdnValidation7=Please+enter+valid+email+address"
                + "+for+applicant+no.&ctl00%24plhMain%24hdnValidation8=Please+enter+valid+GWFNo+for+applicant+no.&ctl00"
                + "%24plhMain%24hdnValidation9=Please+select+Visa+Class+for+applicant+no."
                + "&____Ticket=" + gTicket[threadNo].ToString()
                + "&__EVENTVALIDATION=" + gEventvalidation[threadNo]
                + "&ctl00%24plhMain%24mycaptchacontrol1=" + gVerificationCode[threadNo]
                );
            gTicket[threadNo]++;
            gVerificationCode[threadNo] = "";//不论输入得正确与否, 都需要清空
            gHtml[threadNo] = respHtml;

            reg = @"(?<=name=""__EVENTVALIDATION"" id=""__EVENTVALIDATION"" value="").*?(?="" />)";
            myMatch = (new Regex(reg)).Match(respHtml);
            if (myMatch.Success)
            {
                gEventvalidation[threadNo] = ToUrlEncode(myMatch.Groups[0].Value);
            }
            else
            {
                if (gForceToStop)
                {
                    return -4;
                }
                setLogtRed(threadNo, "getting page failed, retry..");
                goto details;
            }

            reg = @"(?<=id=""__VIEWSTATE"" value="").*?(?="" />)";
            myMatch = (new Regex(reg)).Match(respHtml);
            if (myMatch.Success)
            {
                gViewstate[threadNo] = ToUrlEncode(myMatch.Groups[0].Value);
            }
            else
            {
                if (gForceToStop)
                {
                    return -4;
                }
                setLogtRed(threadNo, "getting page failed, retry..");
                goto details;
            }

            if (respHtml.Contains("Please enter the correct verification code") || respHtml.Contains("Please enter the correct CAPTCHA alphabets"))
            {
                if (gForceToStop)
                {
                    return -4;
                }
                setLogT(threadNo, "验证码错误!请重新输入");
                goto verification1;
            }

            if (respHtml.Contains("申请人已预约") || respHtml.Contains("Marked applicants already have an appointment."))
            {
                setLogtRed(threadNo, "申请人已预约: " + gLastName + " " + gFirstName + ", 护照: " + gPassport);
                return -3;
            }

            if (respHtml.Contains("Applicant Details") && respHtml.Contains("Please enter"))
            {
                setLogT(threadNo, "incompleted personal details");
                return -1;
            }
            if (gDays.Count == 0)
            {
                reg = @"(?<=Appointment',')\d+?(?='\)"" style=""color:Black"" title="")";
                myMatch = (new Regex(reg)).Match(respHtml);
                while (myMatch.Success)
                {
                    gDays.Add(myMatch.Groups[0].Value);
                    myMatch = myMatch.NextMatch();
                }
            }

            if (gDays.Count == 0)
            {
                setLogT(threadNo, gVACity_raw + ", " + (gCategory.Equals("17") ? "working and holiday, " : "general") + ", 名额已满, 请尝试其它预约地点");
                return -5;
            }
            return 1;
        }
        private static List<IIMDbSearchResult> MultipleMatchesAddToSearchResults
            (Match match, IMDbRegEx imDbRegex, List<IIMDbSearchResult> results)
        {

            while (match != null && match.Length > 0)
            {


                var result = IMDbConventionalFilmSearchEngineHelpers
                    .MultipleMatchesMineDetailsOfSingleFilmResult(match, imDbRegex);


                IMDbConventionalFilmSearchEngineHelpers
                    .IgnoreIrrelevantResults
                    (match, imDbRegex, result);


                results.Add(result);
                
                Debugger.LogMessageToFile
                    ("[IMDb Conventional Film Search Engine] " +
                     "Result was added to list.");
                
                match = match.NextMatch();
                
                Debugger.LogMessageToFile
                    ("[IMDb Conventional Film Search Engine]" +
                     " Proceeding to next result...");
            
            }




          return results;
        }
예제 #49
0
        private static IEnumerable<Match> EnumerateMatches(Match match, int count, bool rightToLeft)
        {
            count--;

            if (rightToLeft)
            {
                var matches = new List<Match>();
                while (match.Success)
                {
                    matches.Add(match);

                    count--;

                    if (count == 0)
                        break;

                    match = match.NextMatch();
                }

                for (int i = (matches.Count - 1); i >= 0; i--)
                    yield return matches[i];
            }
            else
            {
                while (match.Success)
                {
                    yield return match;

                    count--;

                    if (count == 0)
                        yield break;

                    match = match.NextMatch();
                }
            }
        }
예제 #50
0
        /// <summary>
        /// Replaces all occurrences of the regex in the string with the
        /// replacement evaluator.
        ///
        /// Note that the special case of no matches is handled on its own:
        /// with no matches, the input string is returned unchanged.
        /// The right-to-left case is split out because StringBuilder
        /// doesn't handle right-to-left string building directly very well.
        /// </summary>
        private static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat)
        {
            if (evaluator == null)
            {
                throw new ArgumentNullException(nameof(evaluator));
            }
            if (count < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
            }
            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
            }

            if (count == 0)
            {
                return(input);
            }

            Match match = regex.Match(input, startat);

            if (!match.Success)
            {
                return(input);
            }
            else
            {
                var vsb = new ValueStringBuilder(stackalloc char[ReplaceBufferSize]);

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    do
                    {
                        if (match.Index != prevat)
                        {
                            vsb.Append(input.AsSpan(prevat, match.Index - prevat));
                        }

                        prevat = match.Index + match.Length;
                        string result = evaluator(match);
                        if (!string.IsNullOrEmpty(result))
                        {
                            vsb.Append(result);
                        }

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat < input.Length)
                    {
                        vsb.Append(input.AsSpan(prevat, input.Length - prevat));
                    }
                }
                else
                {
                    // In right to left mode append all the inputs in reversed order to avoid an extra dynamic data structure
                    // and to be able to work with Spans. A final reverse of the transformed reversed input string generates
                    // the desired output. Similar to Tower of Hanoi.

                    int prevat = input.Length;

                    do
                    {
                        if (match.Index + match.Length != prevat)
                        {
                            vsb.AppendReversed(input.AsSpan(match.Index + match.Length, prevat - match.Index - match.Length));
                        }

                        prevat = match.Index;
                        vsb.AppendReversed(evaluator(match));

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();
                    } while (match.Success);

                    if (prevat > 0)
                    {
                        vsb.AppendReversed(input.AsSpan(0, prevat));
                    }

                    vsb.Reverse();
                }

                return(vsb.ToString());
            }
        }
        public bool TryMatch(string input, Match previousMatch, out Match result)
        {
            if (input == null && previousMatch == null)
                throw new InvalidOperationException("Both input and previousMatch can not be null.");

            if (previousMatch == null)
            {
                System.Text.RegularExpressions.Regex regEx = this.GetRegEx(options);
                result = regEx.Match(input);
            }
            else
            {
                result = previousMatch.NextMatch();
            }
            return result.Success;
        }
예제 #52
0
		/// <summary>
		/// Goes through <paramref name="m"/> matches and fill <paramref name="matches"/> array with results
		/// according to Set Order.
		/// </summary>
		/// <param name="r"><see cref="Regex"/> that produced the match</param>
		/// <param name="m"><see cref="Match"/> to iterate through all matches by NextMatch() call.</param>
		/// <param name="matches">Array for storing results.</param>
		/// <param name="addOffsets">Whether or not add arrays with offsets instead of strings.</param>
		/// <returns>Number of full pattern matches.</returns>
		private static int FillMatchesArrayAllSetOrder(Regex r, Match m, ref PhpArray matches, bool addOffsets)
		{
			// first index, increases at each match in set order
			int i = 0;

			while (m.Success)
			{
				PhpArray pa = new PhpArray(m.Groups.Count, 0);

				// add all groups
				for (int j = 0; j < m.Groups.Count; j++)
				{
					object arr = NewArrayItem(m.Groups[j].Value, m.Groups[j].Index, addOffsets);
					
                    AddGroupNameToResult(r, pa, j, (p, groupName) =>
                    {
                        p[groupName] = arr;
                    });


					pa[j] = arr;
				}

				matches[i] = pa;
				i++;
				m = m.NextMatch();
			}

			return i;
		}
예제 #53
0
        // Update the disk statistics with data for block device on the (major,minor) pair.
        private static void UpdateDiskStats()
        {
            string buffer;

            if (major == 0)
            {
                return;
            }

            // We only refresh the stats once per second
            if ((DateTime.Now - disk_stats_time).TotalSeconds < disk_stats_delay)
            {
                return;
            }

            // Read in all of the disk stats
            using (StreamReader stream = new StreamReader("/proc/diskstats"))
                buffer = stream.ReadToEnd();

            // Find our partition and parse it
            const string REGEX = "[\\s]+{0}[\\s]+{1}[\\s]+[a-zA-Z0-9]+[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([0-9]+)";
            string       regex = String.Format(REGEX, major, minor);
            Regex        r     = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Compiled);

            for (System.Text.RegularExpressions.Match m = r.Match(buffer); m.Success; m = m.NextMatch())
            {
                disk_stats_read_reqs   = Convert.ToInt32(m.Groups[1].ToString());
                disk_stats_read_bytes  = Convert.ToInt32(m.Groups[2].ToString());
                disk_stats_write_reqs  = Convert.ToInt32(m.Groups[3].ToString());
                disk_stats_write_bytes = Convert.ToInt32(m.Groups[4].ToString());
            }

            disk_stats_time = DateTime.Now;
        }