Match() public method

public Match ( string input ) : System.Text.RegularExpressions.Match
input string
return System.Text.RegularExpressions.Match
コード例 #1
0
ファイル: Test.xaml.cs プロジェクト: ishwormali/practices
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string strPattern = @"CM-\w+";

            string strToTest = "CM-2345 implemented";
            string strToTest2 = "Changes in CM-2395";
            string strToTest3 = "Changes for CM-2365 complete and need to change CM-1258 ";
            var regEx = new Regex(strPattern);

            var match1 = regEx.Match(strToTest);

            MessageBox.Show(match1.Success ? match1.Groups[0].Value : "not match " + strToTest);

            var match2 = regEx.Match(strToTest2);
            MessageBox.Show(match2.Success ? match2.Groups[0].Value : "not match " + strToTest2);

            var matches3 = regEx.Matches(strToTest3);
            foreach (Match match3 in matches3)
            {
                foreach (Capture capt in match3.Captures    )
                {
                    MessageBox.Show(string.Format("Index={0}, Value={1}", capt.Index, capt.Value));
                }
            }

            //MessageBox.Show(match3.Success ? match3.Groups[0].Value : "not match " + strToTest3);
            //MessageBox.Show(match3.Success ? match3.Groups[1].Value : "not match " + strToTest3);
        }
コード例 #2
0
ファイル: VariableParser.cs プロジェクト: feihuobuke/xCoder
        public string Build(object parameter)
        {
            var data = parameter.Convert();
            foreach (string variable in Options.VariableCollection)
            {
                if (string.IsNullOrEmpty(data[variable]))
                {
                    data.Add(variable, Options.VariableCollection[variable]);
                }
            }
            Match[] results = Parse();
            string temp = TemplateContent;

            foreach (string item in data.Keys)
            {
                var regx = new Regex(string.Format(ItemRegxFormat, item), RegxOptions);
                List<Match> collection = results.Where(t => t.Success && regx.Match(t.Value).Success).ToList();
                string value = data[item];
                foreach (Match match in collection)
                {
                    Match subMatch = regx.Match(match.Groups[1].Value);
                    var words = new Regex(@"\w", RegxOptions);
                    string g1 = subMatch.Groups[1].Value;
                    string g2 = subMatch.Groups[2].Value;
                    string g3 = subMatch.Groups[3].Value;
                    if (words.Match(g1).Success || words.Match(g3).Success || string.IsNullOrEmpty(g2))
                    {
                        continue;
                    }
                    temp = temp.Replace(match.Value, value);
                }
            }

            return temp;
        }
コード例 #3
0
ファイル: RegExTests.cs プロジェクト: ReitenSchnell/SandBox
 public void Test7()
 {
     var regex = new Regex(@"^\//(\[{1}[^0-9]+\]{1})+[\n]+");
     Assert.Equal("//[***]\n", regex.Match("//[***]\n3***4***5***").Value);
     Assert.Equal("//[***][--]\n", regex.Match("//[***][--]\n3***4***5***").Value);
     Assert.False(regex.IsMatch("22//[***]"));
 }
コード例 #4
0
        public string Format(Component component)
        {
            Regex variable = new Regex("\\$[a-zA-z]+ ");
            string plainVars = variable.Replace(Value, new MatchEvaluator(delegate(Match match)
            {
                string propertyName = match.Value.Replace("$", "").Trim().ToLowerInvariant();
                ComponentProperty propertyInfo = component.FindProperty(propertyName);
                if (propertyInfo != null)
                    return component.GetProperty(propertyInfo).ToString();
                return "";
            }));

            variable = new Regex("\\$[a-zA-Z]+[\\(\\)a-z_0-9]+ ");
            string formattedVars = variable.Replace(plainVars, new MatchEvaluator(delegate(Match match)
            {
                Regex propertyNameRegex = new Regex("\\$[a-zA-z]+");
                string propertyName = propertyNameRegex.Match(match.Value).Value.Replace("$", "").Trim().ToLowerInvariant();
                ComponentProperty propertyInfo = component.FindProperty(propertyName);
                if (propertyInfo != null)
                {
                    return ApplySpecialFormatting(component.GetProperty(propertyInfo), match.Value.Replace(propertyNameRegex.Match(match.Value).Value, "").Trim());
                }
                return "";
            }));

            Regex regex = new Regex(@"\\[uU]([0-9A-F]{4})");
            return regex.Replace(formattedVars, match => ((char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());
        }
コード例 #5
0
ファイル: Identifier.cs プロジェクト: jw56578/WooCompiler
        public void Identifier()
        {
            Regex regex = new Regex(WooCompiler.RegExDefinitions.Identifier);

            it(!regex.Match("3abc").Success);
            it(!regex.Match("@abc").Success);
        }
コード例 #6
0
        public string ProcessContent(string text, string flavor)
        {
            if (string.IsNullOrEmpty(text))
                return string.Empty;

            text = Regex.Replace(text.Replace(FAQGroupStart, FAQGroupStartReplaced), FAQGroupEndRegex, "[/faq_group]", RegexOptions.Multiline);

            text = Regex.Replace(text.Replace(FAQStart, FAQStartReplaced), FAQEndRegex, "[/faq]", RegexOptions.Multiline);

            var regex = new Regex(GetShortcodeRegex("faq_group"), RegexOptions.None);

            var sb = new StringBuilder(text);

            var index = 0;
            var match = regex.Match(text);
            while (match.Success)
            {
                var value = match.Value;
                // Do FAQ Group

                var sbToManipulate = FormatFAQGroup(match, index);
                FormatFAQ(index, sbToManipulate);

                sb = sb.Replace(
                    sb.ToString().Substring(match.Index, match.Length),
                    sbToManipulate.ToString(),
                    match.Index,
                    match.Length);
                match = regex.Match(sb.ToString());
                index++;
            }

            return sb.ToString();
        }
コード例 #7
0
        public ActionResult Index(PatBasicInfor pat)
        {
            PatOperation pto = new PatOperation();

            string PID = Request.Form["门诊号"];
            if (string.IsNullOrEmpty(pat.Name) || string.IsNullOrEmpty(pat.Sex) || string.IsNullOrEmpty(pat.Age) || string.IsNullOrEmpty(pat.Phone))
            {
                ModelState.AddModelError("", "带*的输入项不能为空");
            }
            else
            {
                Regex reg = new Regex("^[0-9]+$");
                Match ma1 = reg.Match(pat.Age);
                Match ma2 = reg.Match(pat.Phone);
                if (ma1.Success && ma2.Success)
                {
                }
                else
                {
                    ModelState.AddModelError("", "手机和年龄必须为数字");
                }
            }
            if (ModelState.IsValid)
            {
                string user;
                user = HttpContext.Request.Cookies["username"].Value.ToString();
                pto.InsertPat(pat, PID, user);
                return RedirectToAction("Index", "Diagnosis", new { ID = pat.Id });
            }
            else
            {
                return View();
            }
        }
コード例 #8
0
        public async Task TestManifest()
        {

            var stream = new MemoryStream();
            var cli = new SpeechClient();
            cli.SetStream(stream);
            await cli.SendManifest();

            stream.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(stream);

            var size = Convert.ToInt32(reader.ReadLine());
            var outp = new char[size];
            reader.ReadBlock(outp, 0, size);

            var str = new String(outp);

            var re = new Regex(@"^([A-Z_]*)");
            Assert.IsTrue(re.Match(str).Value == "APP_MANIFEST");
            var jsonstr = str.TrimStart(re.Match(str).Value.ToCharArray());

            var jsonstream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstr));

            var ser = new DataContractJsonSerializer(typeof(Manifest));
            Manifest jsonobj = (Manifest)ser.ReadObject(jsonstream);
            Assert.IsTrue(jsonobj.Version == "0.0.1");
            Assert.IsTrue(jsonobj.Name == "speech-recognizer");
            Assert.IsTrue(jsonobj.DisplayName == "Mycroft Networked Speech Recognizer");
            Assert.IsTrue(jsonobj.Description == "Lets applications register speech triggers for Mycroft to look for.");
            Assert.IsTrue(jsonobj.InstanceId == "primary");
        }
コード例 #9
0
        public IDisposable Connect(IDataConsumer channel)
        {
            var fileInfo = new FileInfo(_filepath);
            using(FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read)) {
                var buffer = new byte[fileInfo.Length];
                fileStream.Read(buffer, 0, (int) fileInfo.Length);
                int length = (int) fileInfo.Length;
                int offset = 0;

                if(_requestHeaders.ContainsKey(HttpRequestHeader.Range.ToString())) {
                    string range = _requestHeaders[HttpRequestHeader.Range.ToString()];
                    Regex rangeEx = new Regex(@"bytes=([\d]*)-([\d]*)");
                    if(rangeEx.IsMatch(range)) {
                        int from = Convert.ToInt32(rangeEx.Match(range).Groups[1].Value);
                        int to = Convert.ToInt32(rangeEx.Match(range).Groups[2].Value);
                        offset = from;
                        length = (to - from) +1;
                    }
                }
                ArraySegment<byte> data = new ArraySegment<byte>(buffer, offset, length);
                channel.OnData(data, null);

                _log.DebugFormat("Wrote {0} bytes to buffer", data.Array.Length);
                channel.OnEnd();
                return null;
            }
        }
コード例 #10
0
        //When 'Go' button is clicked / main function
        protected void SFButtonClick(object sender, EventArgs e)
        {
            //Regext check input
            Regex numeric09 = new Regex(@"^[0-9]+$");
            Regex alphaAZ = new Regex(@"^[A-Za-z]+$");

            Match matchNumberic09n = numeric09.Match(numeratorInputTxtBox.Text.ToString().Trim());
            Match matchalphaAZn = alphaAZ.Match(numeratorInputTxtBox.Text.ToString().Trim());

            Match matchNumberic09d = numeric09.Match(denominatorInputTxtBox.Text.ToString().Trim());
            Match matchalphaAZd = alphaAZ.Match(denominatorInputTxtBox.Text.ToString().Trim());

            //When regex matches
            if (matchNumberic09n.Success && matchNumberic09d.Success)
            {
                int numerator;
                Int32.TryParse(numeratorInputTxtBox.Text.ToString().Trim(), out numerator);
                int denominator;
                Int32.TryParse(denominatorInputTxtBox.Text.ToString().Trim(), out denominator);

                int GCD = numGCD(numerator, denominator);
                outputLabel.Text = (numerator / GCD).ToString() + " / " + (denominator / GCD).ToString();
            }
            else if (matchalphaAZn.Success && matchalphaAZd.Success)
                outputLabel.Text = lettersFraction(numeratorInputTxtBox.Text.ToString().Trim(), denominatorInputTxtBox.Text.ToString().Trim());
            else
                outputLabel.Text = "Incorrect Input! Please try again!";
        }
コード例 #11
0
ファイル: UrlFactory.cs プロジェクト: coodream/cms
        /// <summary>
        /// 获取文章中的第一张图片,如果没有则返回NULL
        /// </summary>
        /// <param name="html">包含图片标签的内容</param>
        /// <param name="ignoreBase64">是否忽略data:image;base64格式的图片地址</param>
        /// <returns></returns>
        public static string GetFirstPicUri(string html,bool ignoreBase64)
        {
            const string imgTagRegPattern = "<img[^>]*\\bsrc=\"(?<imguri>[^\"]+)\"[^>]*>";

            Regex reg = new Regex(imgTagRegPattern);

            if (reg.IsMatch(html))
            {
                //忽略base64格式的图片
                if (ignoreBase64)
                {
                    //匹配结果
                    string matchResult;

                    foreach (Match match in reg.Matches(html))
                    {
                        matchResult = reg.Match(html).Groups["imguri"].Value;
                        if (!Regex.IsMatch(matchResult, "^data:image/[a-z]+;base64", RegexOptions.IgnoreCase))
                            return matchResult;
                    }

                }
                else
                {
                    return reg.Match(html).Groups["imguri"].Value;
                }
            }
            return null;
        }
コード例 #12
0
ファイル: HttpUtils.cs プロジェクト: zhanglc8801/WKT2015
        /// <summary>
        /// 自动检测内容的charset,通过字符集和html中指定的contentType来获取
        /// 如果无法获得字符集,则返回null
        /// </summary>
        /// <param name="stringcontent"></param>
        /// <returns></returns>
        public static Encoding DetectCharset(QuickWebResponse response, byte[] bytes)
        {
            string regexstr = "(text/html|text/xml).*charset=(?<charset>\\w+\\-*\\d*)";
            Regex regex = new Regex(regexstr, RegexOptions.IgnoreCase);

            string contentType = response.ContentTypeStr;
            if (contentType != null)
            {
                Match match1 = regex.Match(contentType);
                if (match1.Success)
                {
                    string charset = match1.Groups["charset"].Value.ToUpper();
                    Encoding encoder = System.Text.Encoding.GetEncoding(charset);
                    if (encoder != null)
                    {
                        return encoder;
                    }
                }
            }

            string ascii = System.Text.Encoding.ASCII.GetString(bytes);
            //<META http-equiv="Content-Type" content="text/html; charset=GB2312">
            //Content-Type=text/html;

            Match match = regex.Match(ascii);
            if ( match.Success )
            {
                string charset =  match.Groups["charset"].Value.ToUpper();
                return System.Text.Encoding.GetEncoding(charset);
            }
            else {
                return null;
            }
        }
コード例 #13
0
ファイル: TestRegex.cs プロジェクト: anderscui/jieba.NET
        public void TestUserDictRegex()
        {
            var reUserDict = new Regex("^(?<word>.+?)(?<freq> [0-9]+)?(?<tag> [a-z]+)?$", RegexOptions.Compiled);
            var s = "Steve Jobs 1000 nr";
            var mat = reUserDict.Match(s);
            Assert.That(mat.Groups.Count, Is.EqualTo(4));
            Assert.That(mat.Groups["word"].Value.Trim(), Is.EqualTo("Steve Jobs"));
            Assert.That(mat.Groups["freq"].Value.Trim(), Is.EqualTo("1000"));
            Assert.That(mat.Groups["tag"].Value.Trim(), Is.EqualTo("nr"));

            s = "Steve Jobs 1000";
            mat = reUserDict.Match(s);
            Assert.That(mat.Groups.Count, Is.EqualTo(4));
            Assert.That(mat.Groups["word"].Value.Trim(), Is.EqualTo("Steve Jobs"));
            Assert.That(mat.Groups["freq"].Value.Trim(), Is.EqualTo("1000"));
            Assert.That(mat.Groups["tag"].Value.Trim(), Is.EqualTo(""));

            s = "Steve Jobs";
            mat = reUserDict.Match(s);
            Assert.That(mat.Groups.Count, Is.EqualTo(4));
            Assert.That(mat.Groups["word"].Value.Trim(), Is.EqualTo("Steve Jobs"));
            Assert.That(mat.Groups["freq"].Value.Trim(), Is.EqualTo(""));
            Assert.That(mat.Groups["tag"].Value.Trim(), Is.EqualTo(""));
            CollectionAssert.AreEqual(mat.Groups.SubGroupValues(), new [] { "Steve Jobs", "", "" });
        }
コード例 #14
0
 public void IsAnySingleDigit()
 {
     Regex regex = new Regex(WooCompiler.RegExDefinitions.AnySingleDigit);
     it(!regex.Match("").Success);
     it(!regex.Match("x").Success);
     it(regex.Match("1").Success);
 }
コード例 #15
0
ファイル: SetHeaders.cs プロジェクト: stevesloka/bvcms
        private void SetHeaders2(int id)
        {
            var org = DbUtil.Db.LoadOrganizationById(id);
            var shell = "";
            if ((settings == null || !settings.ContainsKey(id)) && org != null)
            {
                var setting = DbUtil.Db.CreateRegistrationSettings(id);
                shell = DbUtil.Content(setting.ShellBs, null);
            }
            if (!shell.HasValue() && settings != null && settings.ContainsKey(id))
                shell = DbUtil.Content(settings[id].ShellBs, null);
            if (!shell.HasValue())
            {
                shell = DbUtil.Content("ShellDefaultBs", "");
                if(!shell.HasValue())
                    shell = DbUtil.Content("DefaultShellBs", "");
            }


            if (shell.HasValue())
            {
                var re = new Regex(@"(.*<!--FORM START-->\s*).*(<!--FORM END-->.*)", RegexOptions.Singleline);
                var t = re.Match(shell).Groups[1].Value.Replace("<!--FORM CSS-->", ViewExtensions2.Bootstrap3Css());
                ViewBag.hasshell = true;
                ViewBag.top = t;
                var b = re.Match(shell).Groups[2].Value;
                ViewBag.bottom = b;
            }
            else
                ViewBag.hasshell = false;
        }
コード例 #16
0
ファイル: RegularService.cs プロジェクト: AllenSteve/Instance
 public void RegularTest()
 {
     Regex r = new Regex("^\\d+");
     Console.WriteLine(r.Match("@").Success);
     Console.WriteLine(r.Match("akb48").Success);
     Console.WriteLine(r.Match("11akb48").Success);
 }
コード例 #17
0
        /// <summary>
        /// Converts references of form A1, B1, C3, DD99 etc to row and col
        /// </summary>
        /// <param name="reference"></param>
        /// <returns>array of two elements 0 index is row num, 1 index is col. Note that the result is 1-based</returns>
        public static int[] ReferenceToColumnAndRow(string reference)
        {
            //split the string into row and column parts
            

            Regex matchLettersNumbers = new Regex("([a-zA-Z]*)([0-9]*)");
            string column = matchLettersNumbers.Match(reference).Groups[1].Value.ToUpper();
            string rowString = matchLettersNumbers.Match(reference).Groups[2].Value;

            //.net 3.5 or 4.5 we could do this awesomeness
            //return reference.Aggregate(0, (s,c)=>{s*26+c-'A'+1});
            //but we are trying to retain 2.0 support so do it a longer way
            //this is basically base 26 arithmetic
            int columnValue = 0;
            int pow = 1;

            //reverse through the string
            for (int i = column.Length - 1; i >= 0; i--)
            {
                int pos = column[i] - 'A' + 1;
                columnValue += pow * pos;
                pow *= 26;
            }

            return new int[2] { int.Parse(rowString), columnValue };
        }
コード例 #18
0
        public static bool Find(this TextEditor editor, Regex find)
        {
            try
            {
                var previous = find.Options.HasFlag(RegexOptions.RightToLeft);

                var start = previous
                    ? editor.SelectionStart
                    : editor.SelectionStart + editor.SelectionLength;

                var match = find.Match(editor.Text, start);
                if (!match.Success) // start again from beginning or end
                {
                    match = find.Match(editor.Text, previous ? editor.Text.Length : 0);
                }

                if (match.Success)
                {
                    editor.Select(match.Index, match.Length);
                    var loc = editor.Document.GetLocation(match.Index);
                    editor.ScrollTo(loc.Line, loc.Column);
                }

                return match.Success;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.ToString());
                return false;
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Oscarbralo/TopBlogCoder
 static void Main(string[] args)
 {
     string s = "";
     Regex r = new Regex(@"//");
     bool loop = false;
     while ((s = Console.ReadLine()) != null)
     {
         string temp = "";
         if (r.IsMatch(s))
         {
             temp = s.Substring(r.Match(s).Index, s.Length - r.Match(s).Index);
             Console.WriteLine(temp);
         }
         else if (s.Contains("*/"))
         {
             Console.WriteLine(s);
             loop = false;
         }
         else if (loop)
         {
             Console.WriteLine(s);
         }
         else if (s.Contains("/*"))
         {
             Console.WriteLine(s);
             loop = true;
         }
     }
     Console.ReadLine();
 }
コード例 #20
0
ファイル: Coder.cs プロジェクト: Emaxan/TI_Laba1_Vizhener
 private static void coder_DoWork(object sender, DoWorkEventArgs e)
 {
     var i = 0;
     switch (Processor.Lang)
     {
         case Languages.Ru:
             foreach (var c in Processor.Text.Where(char.IsLetter))
             {
                 var reg = new Regex(Processor.Key[i].ToString());
                 var reg1 = new Regex(c.ToString());
                 Processor.Cipertext += char.IsLower(c)
                     ? Processor.SmlRus[((reg1.Match(Processor.SmlRus).Index) + reg.Match(Processor.SmlRus).Index) % 33]
                     : Processor.BigRus[((reg1.Match(Processor.BigRus).Index) + reg.Match(Processor.SmlRus).Index) % 33];
                 i++;
                 (sender as BackgroundWorker).ReportProgress(i);
             }
             break;
         case Languages.Eng:
             foreach (var c in Processor.Text.Where(char.IsLetter))
             {
                 Processor.Cipertext += char.IsLower(c)
                     ? Processor.SmlEng[((c - 'a') + (Processor.Key[i] - 'a')) % 26]
                     : Processor.BigEng[((c - 'A') + (Processor.Key[i] - 'a')) % 26];
                 i++;
                 (sender as BackgroundWorker).ReportProgress(i);
             }
             break;
     }
 }
コード例 #21
0
ファイル: RegExTests.cs プロジェクト: ReitenSchnell/SandBox
 public void Test5()
 {
     var regex = new Regex(@"0*[1-9][0-9]*");
     Assert.Equal("00077", regex.Match("00077").Value);
     Assert.Equal("00077", regex.Match("00077bb").Value);
     Assert.Equal("007", regex.Match("007").Value);
 }
コード例 #22
0
ファイル: ShaderPreparser.cs プロジェクト: whztt07/vengine
 public static string Preparse(string filename, string source)
 {
     Regex includeMatcher = new Regex("\\#include (.+)\n");
     Match match = includeMatcher.Match(source);
     while(match.Success)
     {
         string includeFile = Preparse(match.Groups[1].Value.Trim(), Media.ReadAllText(match.Groups[1].Value.Trim()));
         source = source.Remove(match.Index, match.Length);
         source = source.Insert(match.Index, includeFile + "\r\n");
         match = includeMatcher.Match(source);
     }
     Regex includeOnceMatcher = new Regex("\\#include_once (.+)\n");
     var included = new List<string>();
     match = includeOnceMatcher.Match(source);
     while(match.Success)
     {
         string file = match.Groups[1].Value.Trim();
         if(included.Contains(file))
         {
             source = source.Remove(match.Index, match.Length);
         }
         else
         {
             included.Add(file);
             string includeFile = Preparse(match.Groups[1].Value.Trim(), Media.ReadAllText(match.Groups[1].Value.Trim()));
             source = source.Remove(match.Index, match.Length);
             source = source.Insert(match.Index, includeFile + "\r\n");
             match = includeMatcher.Match(source);
         }
     }
     return PrependWithInfo(filename, source);
 }
コード例 #23
0
        public void definingARegex()
        {
            // using "@" before the string is for using "verbatim string literals", it is useful to avoid using escape characters
            // @"C:\GIT\hackerrank-problems" is equals to "C:\\GIT\\hackerrank-problems"

            Regex regex = new Regex(@"x*y"); // x*y

            Match match = regex.Match("xxxy");
            if (match.Success)
                Console.WriteLine("regex: {0} --> match sequence: {1}",regex, match.Value);

            match = regex.Match("cccxxxxxxyyyyy");
            if (match.Success)
                Console.WriteLine("regex: {0} --> match sequence: {1}", regex, match.Value); // there is a match with the last part of the sequence

            // \b is the boundary of the expression, if you don't define the boundary there will match when the sequence contais the regex
            regex = new Regex(@"\bx*y\b");

            match = regex.Match("xxxy");
            if (match.Success)
                Console.WriteLine("regex: {0} --> match sequence: {1}", regex, match.Value);

            match = regex.Match("cccxxxxxxyyyyy");
            if (match.Success)
                Console.WriteLine("regex: {0} --> match sequence: {1}", regex, match.Value);
            else
                Console.WriteLine("regex: {0} --> NOT match sequence: {1}", regex, "cccxxxxxxyyyyy");
        }
コード例 #24
0
        /// <summary>
        /// Parses a language header and returns supported languages
        /// </summary>
        /// <param name="languageHeader"></param>
        /// <returns></returns>
        public List<Language> Parse(String languageHeader)
        {
            if (String.IsNullOrEmpty(languageHeader)) return null;

              var languageArray = languageHeader.Split(',').ToList();
              languageArray = languageArray.Select(la => la.ToLowerInvariant()).ToList();
              var languageRegex = new Regex(@"([a-z]{1,8}(-[a-z]{1,8})?)[,geo]?\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?");

              var languagePreferences = new List<Language>();

              foreach (var language in languageArray)
              {
            if(!languageRegex.Match(language).Success) continue;

            var languageMatches = languageRegex.Match(language).Groups;

              if (CultureExists(languageMatches[1].Value))
              {
              var languagePreference = !String.IsNullOrEmpty(languageMatches[4].Value) ? new Language(languageMatches[1].Value.ToLower(), languageMatches[4].Value) : new Language(languageMatches[1].Value, 1.0d);

              languagePreferences.Add(languagePreference);
              }

              }

              return languagePreferences.Any() ? languagePreferences.OrderByDescending(lp => lp.Preference).ToList() : null;
        }
コード例 #25
0
        public void WillFlushSingleReduction()
        {
            var cssPattern = new Regex(@"<link[^>]+type=""?text/css""?[^>]+>", RegexOptions.IgnoreCase);
            var urlPattern = new Regex(@"href=""?(?<url>[^"" ]+)""?[^ />]+[ />]", RegexOptions.IgnoreCase);
            new WebClient().DownloadString("http://localhost:8877/Local.html");
            WaitToCreateResources();
            var response = new WebClient().DownloadString("http://localhost:8877/Local.html");
            var css = cssPattern.Match(response).ToString();
            var url = urlPattern.Match(css).Groups["url"].Value;
            var key = uriBuilder.ParseKey(url).RemoveDashes();

            new WebClient().DownloadData("http://localhost:8877/RRContent/" + key + "/flush");
            var cssFilesAfterFlush = Directory.GetFiles(rrFolder, "*.css");
            response = new WebClient().DownloadString("http://localhost:8877/Local.html");
            css = cssPattern.Match(response).ToString();
            url = urlPattern.Match(css).Groups["url"].Value;
            var newKey = uriBuilder.ParseKey(url);
            WaitToCreateResources(shouldBeNoExpiredFiles:true);
            var cssFilesAfterRefresh = Directory.GetFiles(rrFolder, "*.css");

            Assert.Equal(Guid.Empty, newKey);
            Assert.Equal(1, cssFilesAfterFlush.Length);
            Assert.True(cssFilesAfterFlush[0].Contains("-Expired-"));
            Assert.Equal(1, cssFilesAfterRefresh.Length);
            Assert.False(cssFilesAfterRefresh[0].Contains("-Expired-"));
        }
コード例 #26
0
        protected static double ParseExpression(string exprString)
        {
            if (string.IsNullOrEmpty(exprString)) return 0;
            exprString = exprString.Replace(" ", string.Empty);
            if (string.IsNullOrEmpty(exprString)) return 0;

            var opRegex = new Regex(@"[\+-]");
            var match1 = opRegex.Match(exprString);
            if (match1.Index == 0)
            {
                return double.Parse(exprString);
            }
            var match2 = opRegex.Match(exprString, match1.Index + 1);

            var result = double.Parse(exprString.Substring(0, match1.Index));
            double nextValue;
            while (match1.Index > 0 && match2.Index > 0)
            {
                nextValue = double.Parse(exprString.Substring(match1.Index + 1, match2.Index - match1.Index - 1));
                if (match1.Value == "-")
                {
                    nextValue = -nextValue;
                }
                result += nextValue;
                match1 = match2;
                match2 = opRegex.Match(exprString, match1.Index + 1);
            }
            nextValue = double.Parse(exprString.Substring(match1.Index + 1));
            if (match1.Value == "-")
            {
                nextValue = -nextValue;
            }
            result += nextValue;
            return result;
        }
コード例 #27
0
 private ParamCollection Parse(ref string s, string pattern, bool remove, string tag, RegexOptions options)
 {
     ParamCollection cmd = new ParamCollection(Name);
     Regex rex = new Regex(pattern, options);
     Match m1 = rex.Match(s);
     while (m1.Success)
     {
         string param = m1.Groups[PARAM].Value;
         string arg = m1.Groups[ARGS].Value;
         if (param != null)
         {
             param = param.TrimEnd(' ');
             ArgCollection prm = cmd.Add(param, new ArgCollection(param, tag));
             if (arg != null)
             {
                 arg = arg.TrimEnd(' ');
                 if (!string.IsNullOrEmpty(arg))
                 {
                     prm.Add(arg);
                 }
             }
         }
         if (remove)
         {
             s = s.Remove(m1.Index, m1.Length).Trim();
             m1 = rex.Match(s);
         }
         else
         {
             m1 = rex.Match(s, m1.Index + m1.Length);
         }
     }
     return cmd;
 }
コード例 #28
0
        /// <summary>
        /// Gets all scripts that should be executed. 
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SqlScript> GetScripts(Func<IDbConnection> connectionFactory)
        {
            var providerRegex = new Regex(@"_(?<Provider>.*?)\.");
            return assembly
                .GetManifestResourceNames()
                .Where(filter)
                .GroupBy(f=> providerRegex.Replace(f, "."))
                .Select(g=>
                            {
                                if (g.Count() == 1)
                                    return g.Single();

                                var matchingProvider = g.FirstOrDefault(
                                    s =>
                                        {
                                            var @group = providerRegex.Match(s).Groups["Provider"];
                                            return @group.Success &&
                                                    @group.Value == databaseProviderName;
                                        });

                                return
                                    matchingProvider ??
                                    g.FirstOrDefault(s => !providerRegex.Match(s).Groups["Provider"].Success);
                            })
                .OrderBy(x => x)
                .Select(ReadResourceAsScript)
                .ToList();
        }
コード例 #29
0
ファイル: SearchTextBox.cs プロジェクト: BAD-AL/NFL2K5Tool
        /// <summary>
        /// Finds the next match of 'SearchString'
        /// </summary>
        /// <returns>The line number it occurs on</returns>
        public int FindNextMatch()
        {
            int retVal = -1;

            if (SearchString != null && !SearchString.Equals(""))
            {
                Regex r;
                r = new Regex(SearchString, RegexOptions.IgnoreCase);
                int startAt = this.SelectionStart + 1;
                if (startAt > this.Text.Length)
                    startAt = 0;

                Match m = r.Match(this.Text, startAt);

                if (m.Length == 0)
                { // continue at the top if not found
                    m = r.Match(this.Text);
                }
                if (m.Length > 0)
                {
                    this.SelectionStart = m.Index;
                    this.SelectionLength = m.Length;
                    retVal = this.GetLineFromCharIndex(this.SelectionStart);
                }
            }
            UpdateStatusControl(retVal);
            return retVal;
        }
コード例 #30
0
 static void Main(string[] args)
 {
     var n = int.Parse(Console.ReadLine());
     var regex1 = new Regex("^hackerrank.*$");
     var regex2 = new Regex("^.*hackerrank$");
     for (var i = 0; i < n; ++i)
     {
         var input = Console.ReadLine();
         if (regex1.Match(input).Success)
         {
             if (regex2.Match(input).Success)
             {
                 Console.WriteLine(0);
             }
             else
             {
                 Console.WriteLine(1);
             }
         }
         else if (regex2.Match(input).Success)
         {
             Console.WriteLine(2);
         }
         else
         {
             Console.WriteLine(-1);
         }
     }
 }
コード例 #31
0
        string RemoveAttributes(string value)
        {
            var attributeClean = new System.Text.RegularExpressions.Regex(@"\<[a-z]+\b([^>]+?)\s?\/?\>", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            while (attributeClean.IsMatch(value))
            {
                var match = attributeClean.Match(value);
                value = value.Remove(match.Index, match.Length);
            }
            return(value);
        }
コード例 #32
0
        public static Match MatchOrNull(this System.Text.RegularExpressions.Regex regex, string input)
        {
            if (input == null)
            {
                return(null);
            }

            var match = regex.Match(input);

            return(match.Success ? match : null);
        }
コード例 #33
0
ファイル: Regex.cs プロジェクト: CCRcmcpe/Crlib
        public static IEnumerable <Match> LazyMatch(this System.Text.RegularExpressions.Regex regex, string input)
        {
            Match match = regex.Match(input);

            while (match.Success)
            {
                yield return(match);

                match = match.NextMatch();
            }
        }
コード例 #34
0
        public void AddError(Task task, bool isError, string errorMessage)
        {
            var match = mcsErrorFormat.Match(errorMessage);

            if (match.Success)
            {
                errorMessage = match.Groups [1].Value;
            }
            errors.Add(new ErrorText(task, isError, errorMessage));
            DisposeLayout();
        }
コード例 #35
0
        public bool TryMatch(string input, RegexOptions options, int startAt, out Match result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            System.Text.RegularExpressions.Regex regEx = this.GetRegEx(options);
            result = regEx.Match(input);
            return(result.Success);
        }
コード例 #36
0
        private void GetAlbumAndURL(Song song)
        {
            try
            {
                buffer = DownloadData(song.Url);

                songsource = encoder.GetString(buffer);

                regex = new Regex("<div id=.artist.>.*?</div>", RegexOptions.Singleline);
                match = regex.Match(songsource);

                if (match.Success)
                {
                    regex = new Regex("href=.*?\".*?\"", RegexOptions.Singleline);
                    match = regex.Match(match.Value);

                    if (match.Success)
                    {
                        song.ArtistUrl      = match.Value.Replace("href=\"", "").Replace("\"", "");
                        linkLabelArtist.URL = song.ArtistUrl;
                    }
                }

                regex = new Regex("<div id=.album.>.*?</div>", RegexOptions.Singleline);
                match = regex.Match(songsource);

                if (match.Success)
                {
                    string albumText = Regex.Replace(match.Value, "<.*?>", "", RegexOptions.Singleline).Replace("\n", "").Replace("\t", "");
                    albumText = System.Xml.XmlConvert.DecodeName(albumText);
                    //HTML Character entities
                    albumText           = albumText.Replace("&quot;", "\"");
                    albumText           = albumText.Replace("&apos;", "'");
                    albumText           = albumText.Replace("&amp;", "&");
                    albumText           = albumText.Replace("&lt;", "<");
                    albumText           = albumText.Replace("&gt;", ">");
                    song.Album          = albumText;
                    linkLabelAlbum.Text = song.Album;

                    regex = new Regex("href=.*?\".*?\"", RegexOptions.Singleline);
                    match = regex.Match(match.Value);

                    if (match.Success)
                    {
                        song.AlbumUrl      = match.Value.Replace("href=\"", "").Replace("\"", "");
                        linkLabelAlbum.URL = song.AlbumUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("TaskbarNotifier: " + ex.Message);
            }
        }
コード例 #37
0
ファイル: ObjGeo.cs プロジェクト: koder05/progs
        /// <summary>
        /// Проверка введенного номера здания на соответствие выражению в КЛАДР
        /// </summary>
        /// <param name="buildingExpr"></param>
        /// <returns></returns>
        public bool BuildingValidate(string buildingExpr)
        {
            string expr = GetNormalizeBuildingString(buildingExpr);

            RegEx.Regex isWholeRegex     = new RegEx.Regex(@"^(?i)[\d\w/-]*$");
            RegEx.Regex isDigitRegex     = new RegEx.Regex(@"^(?<Num>\d+)");
            RegEx.Regex isRangeRegex     = new RegEx.Regex(_buildingRangeRegex);
            RegEx.Regex isEvenRangeRegex = new RegEx.Regex(_buildingEvenRangeRegex);
            RegEx.Regex isOddRangeRegex  = new RegEx.Regex(_buildingOddRangeRegex);

            if (string.IsNullOrEmpty(this.BuildingTemplateString))
            {
                return(isWholeRegex.IsMatch(expr));
            }

            string[] templateList = this.BuildingTemplateString.Split(',');

            //простое сравнение
            foreach (string s in templateList)
            {
                if (expr.Equals(s, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
            }

            //если простое сравнение не удалось, отсеиваем буквы, корпуса и строения (в кладр темплейты номеров домов часто не учитывают букв и корпусов);
            //повторяем прямое сравнение + ищем номер в диапазонах

            //удостоверимся, что выражение на входе есть простое число
            RegEx.Match m = isDigitRegex.Match(expr);
            if (m.Groups["Num"] != null && m.Groups["Num"].Success)
            {
                int number = Convert.ToInt32(m.Groups["Num"].Value);
                foreach (string s in templateList)
                {
                    if (m.Groups["Num"].Value.Equals(s, StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }

                    if (
                        (isRangeRegex.IsMatch(s) && FindNumberInRange(number, s, false, false)) ||
                        (isEvenRangeRegex.IsMatch(s) && FindNumberInRange(number, isEvenRangeRegex.Match(s).Groups["Range"].Value, true, false)) ||
                        (isOddRangeRegex.IsMatch(s) && FindNumberInRange(number, isOddRangeRegex.Match(s).Groups["Range"].Value, false, true))
                        )
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #38
0
        /// <summary>
        /// 转换UTC字符串eg:13 Oct 2014 03:50:20 +0800为日期时间
        /// eg:Mon, 13 Oct 2014 03:50:20 +0800 (CST)
        /// </summary>
        public static DateTime?ToUTCTime(this string dateTime)
        {
            DateTime?result = ToSafeDateTime(dateTime);

            if (result != null)
            {
                return(result);
            }

            Text.RegularExpressions.Regex rgex = new Text.RegularExpressions.Regex(@"(?i)\d+ [a-z]+ \d{4} \d+:\d+:\d+ [-\+]\d+");
            return(ToSafeDateTime(rgex.Match(dateTime).Value));
        }
コード例 #39
0
        public object Execute(KarinEngine engine, FunctionToken token, object pipedObj)
        {
            if (token.Arguments.Length != 1)
            {
                throw new KarinException($"{Name}関数の引数の数が不正です。");
            }

            var ptn = new System.Text.RegularExpressions.Regex($@"{token.Name}\s*\[([\s\S]*)\]");
            var mc  = ptn.Match(token.Text);

            return(mc.Groups[1].Value);
        }
コード例 #40
0
        public static bool ValidateEmail(string email)
        {
            string regex = @"^((\&quot;[^\&quot;\f\n\r\t\v\b]+\&quot;)|([\w\!\#\$\%\&amp;\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&amp;\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$";

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

            Match m = reg.Match(email);

            return(m.Success);
        }
コード例 #41
0
            protected override int Count(int countPatternIndex, string sequences)
            {
                var r     = new CoreFxRegex.Regex(CountPatterns[countPatternIndex]);
                int count = 0;

                for (var m = r.Match(sequences); m.Success; m = m.NextMatch())
                {
                    count++;
                }

                return(count);
            }
コード例 #42
0
 /// <summary>
 /// determent whether it is a number or not
 /// </summary>
 public static bool IsNumeric(object inputObject)
 {
     if (inputObject == null || inputObject == DBNull.Value)
     {
         return(false);
     }
     else
     {
         Regex _isNumber = new System.Text.RegularExpressions.Regex("(^[-+]?\\d+(,?\\d*)*\\.?\\d*([Ee][-+]\\d*)?$)|(^[-+]?\\d?(,?\\d*)*\\.\\d+([Ee][-+]\\d*)?$)");
         return(_isNumber.Match(inputObject.ToString()).Success);
     }
 }
コード例 #43
0
ファイル: Match.cs プロジェクト: miaojiang1/monodevelop-1
		public virtual int[] TryMatch (string text, int matchOffset)
		{
			var match = regex.Match (text, matchOffset);
			if (match.Success) {
				var result = new int[match.Groups.Count];
				for (int i = 0; i < result.Length; i++) {
					result[i] = match.Groups[i].Length;
				}
				return result;
			}
			return emptyMatch;
		}
コード例 #44
0
        public void AddError(bool isError, string errorMessage)
        {
            var match = mcsErrorFormat.Match(errorMessage);

            if (match.Success)
            {
                errorMessage = match.Groups[1].Value;
            }
            errors.Add(new ErrorText(isError, errorMessage));
            CollapseExtendedErrors = errors.Count > 1;
            DisposeLayout();
        }
コード例 #45
0
        public virtual ActionResult ProcessFakeAngularRequest()
        {
            if (AtPreviewMode() && InvalidCrossSiteAuth())
            {
                return(new HttpUnauthorizedResult());
            }

            var url = _httponContextBase.Request.Url;
            var mvcRequestContext = new MvcRequestContext(ControllerContext, ViewData, TempData);

            // look for culture strings
            var absolutePath = url.AbsolutePath.ToLower().Replace("/templates", "").Replace(".html", "").Replace(".htm", "");

            var abs = (absolutePath == "/") ? "/Default" : absolutePath;

            var cultureRegex = new System.Text.RegularExpressions.Regex(@"^\/(?<culture>[a-zA-Z]{2}\-[a-zA-Z]{2})?\/?");
            var result       = cultureRegex.Match(absolutePath);
            var culture      = result.Groups["culture"];

            if (culture.Success && abs.EndsWith(culture.Value))
            {
                abs += "/Index";
            }



            var viewName = string.Format("~/Views{0}.cshtml", abs);

            // Fallback to Index.cshtml if abs file is not found
            if (!System.IO.File.Exists(Server.MapPath(viewName)))
            {
                viewName = string.Format("~/Views{0}.cshtml", abs + "/Index");
            }

            var pageHtmlBuilder = mvcRequestContext.RenderRazorViewToString(viewName: viewName, languageCode: culture.Success ? culture.Value : "", model: new object());



            if (pageHtmlBuilder == null)
            {
                return(HttpNotFound());
            }
            else
            {
                var htmlStr = pageHtmlBuilder.ToString();

                // Remove Layout definition
                var regex     = new Regex("Layout\\s=\\s\\\".*\\.cshtml\";");
                var newMarkup = regex.Replace(htmlStr, "");

                return(Content(newMarkup));
            }
        }
コード例 #46
0
ファイル: HttpCollects.cs プロジェクト: x1987624/SNS
        /// <summary>
        /// 获取html内容中的Title
        /// </summary>
        /// <param name="html">html内容</param>
        /// <param name="ignoreCas">是否忽略大小写</param>
        /// <returns>标签title</returns>
        public static string GetTitle(string html, bool ignoreCas)
        {
            string title = HttpCollects.GetMetaString(html, "<meta name=\"title\"([\\s]*)content=\"", "\"([\\s]*)/?>", ignoreCas);

            if (string.IsNullOrEmpty(title))
            {
                string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)";
                System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                return(ex.Match(html).Value.Trim());
            }
            return(title);
        }
コード例 #47
0
        public string GetStrongNameKey()
        {
            var fullname = AssemblyName.GetAssemblyName(this.DllPath).FullName;
            var pattern = "PublicKeyToken=([\\w]*)";
            var regex = new System.Text.RegularExpressions.Regex(pattern);
            var match = regex.Match(fullname); var sn = "";

            if (match.Success)
            {
                sn = match.Groups[1].Value;
            }
            return(sn);
        }
コード例 #48
0
        /// <summary>
        /// Validar o formato de entrada para e-mail
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>

        public static bool ValidarEmailRegEx(string email)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*)([.][A-Za-z]{2,4})$");
            System.Text.RegularExpressions.Match m = r.Match(email);
            if (m.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #49
0
ファイル: Match.cs プロジェクト: yayanyang/monodevelop
        public virtual int TryMatch(string text, int matchOffset)
        {
//			System.Text.RegularExpressions.Match match = regex.Match (text, matchOffset);
            string matchStr = text.Substring(matchOffset);

            System.Text.RegularExpressions.Match match = regex.Match(matchStr);

            if (match.Success)
            {
                return(match.Length);
            }
            return(-1);
        }
コード例 #50
0
 //日期
 private DateTime dateCleaner(string date)
 {
     System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\d{4}/\d{2}/\d{2}");
     if (r.IsMatch(date))
     {
         date = r.Match(date).Value;
     }
     else
     {
         date = "1900/01/01";
     }
     return(DateTime.Parse(date));
 }
コード例 #51
0
ファイル: HttpProc_CN.cs プロジェクト: cupid0426/MyProject
 ///<summary>
 ///分析文本域,添加到请求流
 ///</summary>
 ///<param name="textField">文本域</param>
 private void WriteTextField(string textField)
 {
     string[] strArr = RE.Split(textField, "&");
     textField = "";
     foreach (string var in strArr)
     {
         Match M = RE.Match(var, "([^=]+)=(.+)");
         textField += "--" + BOUNDARY + "\r\n";
         textField += "Content-Disposition: form-data; name=\"" + M.Groups[1].Value + "\"\r\n\r\n" + M.Groups[2].Value + "\r\n";
     }
     byte[] buffer = encoding.GetBytes(textField);
     postStream.Write(buffer, 0, buffer.Length);
 }
コード例 #52
0
ファイル: Web.cs プロジェクト: kiichi54321/Rawler
 public static string GetTitleForHTML(string html)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<title>([^<]*)</title>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Match match = regex.Match(html);
     if (match.Groups.Count > 0)
     {
         return(match.Groups[1].Value);
     }
     else
     {
         return("");
     }
 }
コード例 #53
0
ファイル: HomeController.cs プロジェクト: robinson/mix.core
        private void HandleSeoName(ref string seoName)
        {
            string regex = @"^([A-Za-z]{1,8}|[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})|[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})(-[A-Za-z0-9]{1,8}))\/(.*)$";

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(regex, RegexOptions.IgnoreCase);
            Match m = r.Match(seoName);

            if (m.Success)
            {
                culture = m.Groups[1].Value;
                seoName = m.Groups[5].Value;
            }
        }
コード例 #54
0
ファイル: GlobalVariable.cs プロジェクト: iot369/dailymanager
        /// <summary>
        /// 从阴历创建日历实体
        /// </summary>
        /// <param name="date">表示阴历日期的8位数字,例如:20070209</param>
        /// <param name="IsLeapMonth">是否闰月</param>
        public static ChineseCalendarInfo FromLunarDate(string date, bool IsLeapMonth)
        {
            Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{7}(\d)$");
            Match mc = rg.Match(date);

            if (!mc.Success)
            {
                throw new Exception("日期字符串输入有误!");
            }
            DateTime dt = DateTime.Parse(string.Format("{0}-{1}-{2}", date.Substring(0, 4), date.Substring(4, 2), date.Substring(6, 2)));

            return(FromLunarDate(dt, IsLeapMonth));
        }
コード例 #55
0
            static public string GetFileName(string fileName)
            {
                //用正则表达式删除原有无用符号
                string strRegex = "[\\w\u4e00-\u9fa5\uf900-\ufa2d]+";

                System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(strRegex);
                Match  m            = re.Match(fileName);
                string trueFileName = m.Value;

                fileName = trueFileName;
                //+DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
                return(fileName);
            }
コード例 #56
0
ファイル: Form1.cs プロジェクト: paul-laird/Regex-1
        private void button1_Click(object sender, EventArgs e)
        {
            string s = txtHaystack.Text;

            System.Text.RegularExpressions.Regex r =
                new System.Text.RegularExpressions.Regex(txtNeedle.Text);
            Match m = r.Match(s);

            while (m.Success)
            {
                MessageBox.Show("Found at: " + m.Index);
                m = m.NextMatch();
            }
        }
コード例 #57
0
ファイル: General.cs プロジェクト: ymgeneral/PopLarCloud
        /// <summary>
        /// 生成Sec-WebSocket-Accept
        /// </summary>
        /// <param name="handShakeText">客户端握手信息</param>
        /// <returns>Sec-WebSocket-Accept</returns>
        public static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength)
        {
            string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
            string key           = string.Empty;

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"Sec-WebSocket-Key:(.*?)\r\n");
            System.Text.RegularExpressions.Match m = r.Match(handShakeText);
            if (m.Groups.Count != 0)
            {
                key = System.Text.RegularExpressions.Regex.Replace(m.Value, @"Sec-WebSocket-Key:(.*?)\r\n", "$1").Trim();
            }
            byte[] encryptionString = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
            return(Convert.ToBase64String(encryptionString));
        }
コード例 #58
0
ファイル: Web.cs プロジェクト: kiichi54321/Rawler
        public static string GetParameter(string text, string ParameterName)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(ParameterName + "[ ]*=[\"|\'| ]*(.+?)[\"|\'| |$]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            var r = regex.Match(text);

            if (r.Success)
            {
                return(r.Groups[1].Value);
            }
            else
            {
                return(null);
            }
        }
コード例 #59
0
ファイル: test.cs プロジェクト: zwkjgs/XKD
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string text = null;

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<return_msg><!\\[CDATA\\[(?<code>(.*))\\]\\]></return_msg>");
            System.Text.RegularExpressions.Match match = regex.Match(text);
            string arg_1A_0 = string.Empty;

            if (match.Success)
            {
                text = match.Groups["code"].Value;
            }
            base.Response.Write(text);
        }
コード例 #60
0
ファイル: RegexHelper.cs プロジェクト: tongxin3267/alabo
        public static bool CheckEmail(string mail)
        {
            if (mail.IsNullOrEmpty())
            {
                return(false);
            }
            //if (mail.Length != 11) {
            //    return false;
            //}
            var rg = new System.Text.RegularExpressions.Regex(RegularExpressionHelper.Email);
            var m  = rg.Match(mail);

            return(m.Success);
        }