public string Handle(string input, Match match, IListener listener) { var query = match.Groups[1].Value; var tl = new TorrentLeech(); var results = tl.Search(query); var res = string.Empty; var count = 0; foreach(var result in results) { if (count > 7) break; res += count++ + ": " + result.Title + ": " + result.Size + " MB" + Environment.NewLine; } Brain.Pipe.ListenNext((input2, match2, listener2) => { if (match2.Value == "cancel" || match2.Value == "none" || match2.Value == "nevermind") return "Cancelled"; var index = -1; int.TryParse(match2.Groups[1].Value, out index); if (index == -1 || index >= results.Count) return "Cancelled"; var selected = results[index]; selected.Download(); return "Downloading: " + selected.Friendly; }, "cancel|none|nevermind", @"download (\d+)"); return res; }
protected string InjectAssets(string markup, Match match) { if (match == null) { return markup; } using (var writer = new StringWriter()) { writer.Write(markup.Substring(0, match.Index)); WriteLinks(writer, @"<link type=""text/css"" rel=""stylesheet"" href=""{0}"" />", Compressor.CompressCss(GetSources(CssLinks))); WriteInlines(writer, "<style>", "</style>", CssInlines); WriteLinks(writer, @"<script type=""text/javascript"" src=""{0}""></script>", Compressor.CompressJavascript(GetSources(JavascriptLinks))); WriteInlines(writer, @"<script type=""text/javascript"">", "</script>", JavascriptInlines); WriteInlines( writer, @"<script type=""text/javascript"">jQuery(document).ready(function () {", "});</script>", DomReadyInlines); writer.Write(markup.Substring(match.Index)); return writer.ToString(); } }
/// <summary> /// Initializes a new isntance of the <see cref="RegexLexerContext"/> class /// </summary> /// <param name="position">the position into the source file</param> /// <param name="match">the regular expression match data</param> /// <param name="stateStack">The stack of states</param> /// <param name="ruleTokenType">The token type the rule specified to emit</param> public RegexLexerContext(int position, Match match, Stack<string> stateStack, TokenType ruleTokenType) { Position = position; Match = match; StateStack = stateStack; RuleTokenType = ruleTokenType; }
public IEnumerable<string> Handle(string input, Match match, IListener listener) { var tl = new TorrentLeech(); var movies = tl.GetEntries(TorrentLeech.Movies).Distinct().Take(20).ToArray(); var names = movies.Select(o => o.Friendly).ToArray(); Brain.Pipe.ListenOnce((i, m, l) => { var movie = m.Groups[1].Value; var entry = movies.FirstOrDefault(o => o.Friendly.ToLower().Contains(movie)); if(entry == null) return; if(!entry.Download()) { Brain.Pipe.ListenNext((s, match1, listener1) => { if (match1.Value == "yes") { entry.Download(true); listener1.Output(Speech.Yes.Parse()); listener1.Output("I shall redownload it."); return; } listener1.Output(Speech.Yes.Parse()); listener1.Output("I won't redownload it."); }, "yes", "no"); l.Output("You've already downloaded that sir. Do you want to redownload it?"); } else { l.Output("Downloading " + entry.Friendly + "..."); } }, "download (.+)"); yield return "Here are the latest films. Do you want to download any of them?"; yield return string.Join(", ", names) + "\r\n"; }
protected override NextInstruction OnFieldMatch(RecorderContext context, string source, ref Match match) { var ins=baseRecorder.OnFieldMatchPublic(context, source, ref match); if (ins == NextInstruction.Return) context.FieldBuffer[context.SourceHeaderInfo["__full_text"]] = source; return ins; }
public override string TranslateLambda( string codeLine, Match lambdaMatch ) { var part0 = codeLine.Substring( 0, lambdaMatch.Groups[1].Length - 2 ); var part2 = lambdaMatch.Groups[2].Captures[0].Value; var part1 = (lambdaMatch.Groups[1].Captures[0].Value.Trim().EndsWith( "()", StringComparison.OrdinalIgnoreCase ) ? null : ", "); return string.Format("{0}{1}delegate{2}{{", part0, part1, part2); }
public string Replace(Match m) { Console.WriteLine("WARNING: Assume equality: "); Console.WriteLine(m_SrcStr); Console.WriteLine(m.Groups[1].Captures[0].ToString()); // this.ReplacedContent = m.Groups[1].Captures[0].ToString(); //replace text from PO filde by text from sources return "_('" + m_ReplaceBy + "')"; }
private string LinkEvaluator(Match match, bool prefixLinks) { string mdUrlTag = match.Groups[0].Value; string rawUrl = match.Groups[2].Value; //Escpae external URLs if (rawUrl.StartsWith("http") || rawUrl.StartsWith("https") || rawUrl.StartsWith("ftp")) return mdUrlTag; //Escape anchor links if (rawUrl.StartsWith("#")) return mdUrlTag; //Correct internal image links if (rawUrl.StartsWith("../images/")) return mdUrlTag.Replace("../images/", "images/"); //Used for main page to correct relative links if (prefixLinks) { string temp = string.Concat("/documentation/", rawUrl); mdUrlTag = mdUrlTag.Replace(rawUrl, temp); } if (rawUrl.EndsWith("index.md")) mdUrlTag = mdUrlTag.Replace("/index.md", "/"); else mdUrlTag.TrimEnd('/'); return mdUrlTag.Replace(rawUrl, rawUrl.EnsureNoDotsInUrl()); }
private static Match[] MatchSubstring(string i_source, string i_matchPattern, bool i_uniqueMatch) { //<note> use RegexOptions.Multiline, otherwise it will treat the whole thing as 1 string Regex regex = new Regex(i_matchPattern, RegexOptions.Multiline); MatchCollection matchCollection = regex.Matches(i_source); Match[] result; if (!i_uniqueMatch) { result = new Match[matchCollection.Count]; matchCollection.CopyTo(result, 0); } else { //<note> cannot use HashSet<Match> because each Match object is unique, even though they may have same value (string). Can use HashSet<string> //SortedList is more like sorted Dictionary<key, value> SortedList uniqueMatchCollection = new SortedList(); foreach(Match match in matchCollection) { if (!uniqueMatchCollection.ContainsKey(match.Value)) { uniqueMatchCollection.Add(match.Value, match); } } result = new Match[uniqueMatchCollection.Count]; uniqueMatchCollection.Values.CopyTo(result, 0); //<note> cannot use uniqueMatchCollection.CopyTo(...) since SortedList member is not type-match with destination array member } Console.WriteLine("Found {0} matches", result.Length); return result; }
public BindingMatch(StepBinding stepBinding, Match match, object[] extraArguments, StepArgs stepArgs) { StepBinding = stepBinding; Match = match; ExtraArguments = extraArguments; StepArgs = stepArgs; }
private string MacroAttributeEvaluator(Match m, bool toUnique, Item item) { var value = m.Groups["attributeValue"].Value.ToString(); var alias = m.Groups["attributeAlias"].Value.ToString(); if (toUnique){ int id = 0; if (int.TryParse(value, out id)) { Tuple<Guid,Guid> reference = PersistenceManager.Default.GetUniqueIdWithType(id); if (reference != null) { value = reference.Item1.ToString(); if (this.RegisterNodeDependencies){ var provider = ItemProviders.NodeObjectTypes.GetCourierProviderFromNodeObjectType(reference.Item2); if (provider.HasValue) item.Dependencies.Add(value, provider.Value); } } } }else{ Guid guid = Guid.Empty; if (Guid.TryParse(value, out guid)) { int id = PersistenceManager.Default.GetNodeId(guid); if (id != 0) value = id.ToString(); } } // Get the matched string. return alias + "=\"" + value + "\""; }
internal RegExpMatch(ArrayPrototype parent, Regex regex, Match match, string input) : base(parent, typeof(RegExpMatch)) { this.hydrated = false; this.regex = regex; this.matches = null; this.match = match; base.SetMemberValue("input", input); base.SetMemberValue("index", match.Index); base.SetMemberValue("lastIndex", (match.Length == 0) ? (match.Index + 1) : (match.Index + match.Length)); string[] groupNames = regex.GetGroupNames(); int num = 0; for (int i = 1; i < groupNames.Length; i++) { string name = groupNames[i]; int num3 = regex.GroupNumberFromName(name); if (name.Equals(num3.ToString(CultureInfo.InvariantCulture))) { if (num3 > num) { num = num3; } } else { Group group = match.Groups[name]; base.SetMemberValue(name, group.Success ? group.ToString() : null); } } this.length = num + 1; }
private static string CleanupMatch(Match match) { if(match.Groups["a"].Success) return match.Groups["a"].Value.ToUpper(); return match.Groups["b"].Success ? match.Groups["b"].Value : string.Empty; }
private string MacroElementEvaluator(Match m, bool toUnique, Item item, bool oldSyntax) { // Get the matched string. var element = m.ToString(); var alias = ""; if(oldSyntax) alias = getAttributeValue(m.ToString(), "macroAlias"); else alias = getAttributeValue(m.ToString(), "alias"); if (!string.IsNullOrEmpty(alias)) { var attributesToReplace = MacroAttributesWithPicker(alias); if (this.RegisterMacroDependencies) item.Dependencies.Add(alias, ItemProviders.ProviderIDCollection.macroItemProviderGuid); foreach (var attr in attributesToReplace) { string regex = string.Format("(?<attributeAlias>{0})=\"(?<attributeValue>[^\"]*)\"", attr); Regex rx = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); element = rx.Replace(element, match => MacroAttributeEvaluator(match, toUnique, item)); } } return element; }
public void Transform(Match match, MarkdownReplacementArgs args) { args.Output.Append("<p>"); args.Encoding.Transform(args, match.Matches[0]); args.Output.AppendUnixLine("</p>"); args.Output.AppendUnixLine(); }
public void GetBlobNameTest() { // Arrange string iotHub = "foo.azure-devices.net"; string deviceId = "abcd"; string id = "pqr"; string extension = "json.gz"; var regex = new Regex(BlobNameRegexPattern); var azureBlobLogsUploader = new AzureBlobRequestsUploader(iotHub, deviceId, Mock.Of <IAzureBlobUploader>()); // Act string blobName = azureBlobLogsUploader.GetBlobName(id, AzureBlobRequestsUploader.GetLogsExtension(LogsContentEncoding.Gzip, LogsContentType.Json)); // Assert Assert.NotNull(blobName); Match match = regex.Match(blobName); Assert.True(match.Success); string receivedIotHub = match.Groups["iothub"].Value; string receivedDeviceId = match.Groups["deviceid"].Value; string receivedId = match.Groups["id"].Value; string receivedTimestamp = match.Groups["timestamp"].Value; string receivedExtension = match.Groups["extension"].Value; Assert.Equal(id, receivedId); Assert.Equal(iotHub, receivedIotHub); Assert.Equal(deviceId, receivedDeviceId); Assert.Equal(extension, receivedExtension); Assert.True(DateTime.UtcNow - DateTime.ParseExact(receivedTimestamp, "yyyy-MM-dd--HH-mm-ss", CultureInfo.InvariantCulture) < TimeSpan.FromSeconds(10)); }
public override SearchResult SearchBackward(System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) { if (regex == null || String.IsNullOrEmpty(searchRequest.SearchPattern)) { return(null); } System.Text.RegularExpressions.Match found = null; System.Text.RegularExpressions.Match last = null; foreach (System.Text.RegularExpressions.Match match in regex.Matches(args.Text)) { if (match.Index < fromOffset) { found = match; } last = match; } bool wrapped = false; if (found == null) { found = last; wrapped = true; } if (found != null) { return(new SearchResult(found.Index, found.Length, wrapped)); } return(null); }
public RegularShot(string text, HtmlNodeCollection urlNodes, bool made, int points) : base(urlNodes, made, points) { Regex pattern = new Regex(ShotPattern); System.Text.RegularExpressions.Match match = pattern.Match(text); if (match.Success) { string distanceString = match.Groups["distance"].Value; Distance = int.Parse(distanceString); } if (urlNodes.Count == 1) { return; } if (text.Contains("assist")) { AssistingPlayer = EventFactory.GetLinkFromUrlNode(urlNodes[1]); } else if (text.Contains("block")) { BlockingPlayer = EventFactory.GetLinkFromUrlNode(urlNodes[1]); } else { throw new Exception($"unknown 2nd player role in shooting event"); } }
public async Task <IActionResult> searchEvents(eventPoints eventPoints) { try { Regex regex = new Regex(@"^\-?\d+\.?\d*$"); System.Text.RegularExpressions.Match latitude = regex.Match(eventPoints.latitude); System.Text.RegularExpressions.Match longitude = regex.Match(eventPoints.longitude); if (latitude.Success & longitude.Success) { using (var client = new HttpClient()) { string url = "https://www.eventbriteapi.com/v3/events/search/?location.within=5km&location.longitude=" + longitude + "&location.latitude=" + eventPoints.latitude + "&categories=" + eventPoints.categories.Replace(",", "%2C") + "&date_modified.range_end=" + eventPoints.from.Replace(":", "%3A") + "&token=" + Common.EventToken(); //string url = "https://www.eventbriteapi.com/v3/events/search/?location.within=5km&location.longitude=" + longitude + "&location.latitude=" + eventPoints.latitude + "&categories=" + category + "&start_date.range_start=" + from + "&start_date.range_end=" + eventPoints.to.Replace(":", "%3A") + "&token=" + Common.EventToken(); var response = await client.GetStringAsync(url); return(Ok(response)); } } else { return(StatusCode((int)HttpStatusCode.InternalServerError, new { ErrorMessage = "Invalid latitude/longitude" })); } } catch (Exception e) { string SaveErrorLog = SpiritMeter.Data.Common.SaveErrorLog("searchEvents", e.Message); return(StatusCode((int)HttpStatusCode.InternalServerError, new { ErrorMessage = e.Message })); } }
protected override Guid MatchToGuid(Match m) { System.Net.IPAddress ip; Guid guid = Guid.Empty; if (System.Net.IPAddress.TryParse(m.Value, out ip)) TryToGuid(ip.GetAddressBytes(), out guid); return guid; }
public void GetHtml_CreatesNewCookieValueIfCookieExistsButIsNotValid() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext("invalid"); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.IsTrue(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.IsNotNull(cookie, "Cookie was not set correctly."); Assert.IsTrue(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.IsTrue(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.AreEqual("/", cookie.Path, "Path should have remained at '/' by default."); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.AreEqual(formTokenValue, cookieTokenValue, "Form and cookie token values did not match."); }
///<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); }
private string ResolveUrlPath(string virtualPath, Match m) { if (m.Success && m.Groups[1].Success) { var path = m.Groups[1].Value.Trim().Trim('\'', '"'); if (path.StartsWith("data:", StringComparison.InvariantCultureIgnoreCase)) { return m.Value; } if (Uri.IsWellFormedUriString(path, UriKind.Relative)) { path = VirtualPathUtility.Combine(VirtualPathUtility.GetDirectory(virtualPath), path); } else if (path.StartsWith(Uri.UriSchemeHttp)) { path = new Uri(path).PathAndQuery; } if (HostingEnvironment.ApplicationVirtualPath != "/" && path.StartsWith(HostingEnvironment.ApplicationVirtualPath)) { path = path.Substring(HostingEnvironment.ApplicationVirtualPath.Length); } if (path.StartsWith("/")) { path = "~" + path; } path = VirtualPathUtility.MakeRelative(bundlepath, path).ToLowerInvariant(); return m.Value.Replace(m.Groups[1].Value, "\"" + path + "\""); } return m.Value; }
public static string GetLocalIP() { string result = RunApp("route", "print", true); System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); if (match.Success) { return(match.Groups[2].Value); } else { try { System.Net.Sockets.TcpClient cli = new System.Net.Sockets.TcpClient(); cli.Connect(conndomain, 80); string ip = ((System.Net.IPEndPoint)cli.Client.LocalEndPoint).Address.ToString(); cli.Close(); return(ip); } catch (Exception) { return(null); } } }
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(); } }
/// <summary> /// Converts the string representation of a Guid to its Guid /// equivalent. A return value indicates whether the operation /// succeeded. /// </summary> /// <param name="s">A string containing a Guid to convert.</param> /// <param name="result"> /// When this method returns, contains the Guid value equivalent to /// the Guid contained in <paramref name="s"/>, if the conversion /// succeeded, or <see cref="Guid.Empty"/> if the conversion failed. /// The conversion fails if the <paramref name="s"/> parameter is a /// <see langword="null" /> reference (<see langword="Nothing" /> in /// Visual Basic), or is not of the correct format. /// </param> /// <value> /// <see langword="true" /> if <paramref name="s"/> was converted /// successfully; otherwise, <see langword="false" />. /// </value> /// <exception cref="ArgumentNullException"> /// Thrown if <pararef name="s"/> is <see langword="null"/>. /// </exception> public static bool GuidTryParse(string s, out Guid result) { if (s == null) { throw new ArgumentNullException("s"); } regEx.Regex format = new regEx.Regex( "^[A-Fa-f0-9]{32}$|" + "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" + "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$"); regEx.Match match = format.Match(s); if (match.Success) { result = new Guid(s); return(true); } else { result = Guid.Empty; return(false); } }
// Match evaluators: public string DefaultSortMatchEvaluator(Match match) { FoundDefaultSort = true; if (match.Groups["key"].Captures.Count > 0) DefaultSortKey = match.Groups["key"].Captures[0].Value.Trim(); return ""; }
public async Task<ImageInfo[]> GetImages(Match match) { var username = match.Groups[1].Value; var id = match.Groups[2].Value; var info = await this._memoryCache.GetOrSet( "hatenafotolife-" + username + "/" + id, () => this.Fetch(username, id) ).ConfigureAwait(false); var result = new ImageInfo(); var baseUri = "http://cdn-ak.f.st-hatena.com/images/fotolife/" + username.Substring(0, 1) + "/" + username + "/" + id.Substring(0, 8) + "/" + id; if (info.Extension == "flv") { result.VideoFull = result.VideoLarge = result.VideoMobile = baseUri + ".flv"; result.Full = result.Large = baseUri + ".jpg"; } else { result.Large = baseUri + "." + info.Extension; result.Full = info.IsOriginalAvailable ? baseUri + "_original." + info.Extension : result.Large; } result.Thumb = baseUri + "_120.jpg"; return new[] { result }; }
private static MatchSingleDetail SelectSingle(Match match, string input) { var wholeMatch = match.Groups[0]; string id = match.Groups["source"].Value.Trim(); if (!PathUtility.IsVaildFilePath(id)) { Logger.Log(LogLevel.Warning, $"{id} is not a valid file path, ignored."); return null; } string rangeStr = match.Groups["line"].Value.Trim(); var range = ExtractRange(rangeStr); var idWithRange = string.Format("{0}[{1}-{2}]", id, range.Item1, range.Item2 >= 0 ? range.Item2.ToString() : string.Empty); var location = Location.GetLocation(input, wholeMatch.Index, wholeMatch.Length); // NOT CORRECT NOW: For code snippet, id is the file path, should be case insensitive // NOTE: For code snippet, it is case sensitive for cross-platform compatability return new MatchSingleDetail { Id = idWithRange.BackSlashToForwardSlash(), Path = id, MatchedSection = new Section { Key = wholeMatch.Value, Locations = new List<Location> { location } }, StartLine = range.Item1, EndLine = range.Item2 }; }
bool TryBatchImageHex(ref string line) { System.Text.RegularExpressions.Match match = RegexCache.Match(line, @"[A-Za-z0-9_]+=0x[A-Za-z0-9]+//0x([A-Za-z0-9]+)"); if (match.Groups.Count < 1) { return(false); } bool found = false; for (int n = 1; n < match.Groups.Count; n++) { string v = match.Groups[n].Value; uint addr = U.atoh(v); if (addr < 0x100) { continue; } this.Address.Text = U.ToHexString(addr); AutoSearch(); bool isNearMatch; if (!IsDataFound(out isNearMatch)) {//見つからなかった continue; } found = true; string newV = v + "(0x" + OtherROMAddressWithLDRRef.Text + "//0x" + OtherROMAddressWithLDR.Text + ",0x" + OtherROMRefPointer2.Text + "//0x" + OtherROMAddress2.Text + ")"; line = line.Replace(v, newV); } return(found); }
static SeriesInfo ParseSeries(Match ma) { SeriesInfo info = new SeriesInfo(); Group group = ma.Groups[GROUP_SERIES]; if (group.Length > 0) info.Series = SeriesInfo.CleanupWhiteSpaces(group.Value); group = ma.Groups[GROUP_EPISODE]; if (group.Length > 0) info.Episode = SeriesInfo.CleanupWhiteSpaces(group.Value); group = ma.Groups[GROUP_SEASONNUM]; int tmpInt; if (group.Length > 0 && int.TryParse(group.Value, out tmpInt)) info.SeasonNumber = tmpInt; // There can be multipe episode numbers in one file group = ma.Groups[GROUP_EPISODENUM]; if (group.Length > 0) { foreach (Capture capture in group.Captures) { int episodeNum; if (int.TryParse(capture.Value, out episodeNum)) info.EpisodeNumbers.Add(episodeNum); } } return info; }
/// <summary> /// 验证18位身份证格式 /// </summary> /// <param name="cid"></param> /// <returns>返回字符串,出错信息</returns> public string CheckCidInfo18(string cid) { string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; double iSum = 0; System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|X|x)$"); System.Text.RegularExpressions.Match mc = rg.Match(cid); if (!mc.Success) { return("- 您的身份证号码格式有误!"); } cid = cid.ToLower(); cid = cid.Replace("x", "a"); if (aCity[int.Parse(cid.Substring(0, 2))] == null) { return("- 您的身份证号码格式有误!");//非法地区 } try { DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2)); } catch { return("- 您的身份证号码格式有误!");//非法生日 } for (int i = 17; i >= 0; i--) { iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber); } if (iSum % 11 != 1) { return("- 您的身份证号码格式有误!"); //非法证号 } return(""); }
/// <summary> /// Get the command args like /output:abc" /// </summary> /// <returns></returns> static Dictionary <string, string[]> GetNamedArgList() { Dictionary <string, string[]> namedArgs = new Dictionary <string, string[]>(); string[] args = Environment.GetCommandLineArgs(); foreach (string arg in args) { Regex regex = new Regex("[/{1}](?<key>[^:]+):(?<value>[^\"]*)"); System.Text.RegularExpressions.Match match = regex.Match(arg); if (match.Success) { string strKey = match.Result("${key}").ToLower(); string strValue = match.Result("${value}"); strKey = strKey.Trim('"'); //Remove ? string[] values; if (!namedArgs.TryGetValue(strKey, out values)) { values = new string[0]; namedArgs.Add(strKey, values); } string[] newValues = new string[values.Length + 1]; values.CopyTo(newValues, 0); newValues[values.Length] = strValue; namedArgs[strKey] = newValues; } } return(namedArgs); }
public string Handle(string input, Match match, IListener listener) { var output = ScheduleTicker.Instance.Tasks .Where(o => o.DateTime < DateTime.Now.AddDays(2)) .Aggregate("", (current, task) => current + (task.Description + " at " + task.DateTime.ToShortTimeString() + Environment.NewLine)); return output.Trim(); }
public ParseStepResult ParseMatchForResult(Match matched) { var parsed = GetParsedEntities(matched); var notParsed = matched.Groups[3].Value; return new ParseStepResult(parsed, notParsed); }
/// <summary> /// Obté la resposta de la web i si la codificació no es correcta ho arregla /// </summary> /// <param name="response"></param> private void SetEncodingFromHeader(HttpWebResponse response) { string name = (string)null; if (string.IsNullOrEmpty(response.CharacterSet)) { System.Text.RegularExpressions.Match match = Regex.Match(response.ContentType, ";\\s*charset\\s*=\\s*(?<charset>.*)", RegexOptions.IgnoreCase); if (match.Success) { name = match.Groups["charset"].Value.Trim('\'', '"'); } } else { name = response.CharacterSet; } if (string.IsNullOrEmpty(name)) { return; } try { this.Encoding = Encoding.GetEncoding(name); } catch (ArgumentException ex) { } }
/// <summary> /// 验证15位身份证格式 /// </summary> /// <param name="cid"></param> /// <returns></returns> public string CheckCidInfo15(string cid) { string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{15}$"); System.Text.RegularExpressions.Match mc = rg.Match(cid); if (!mc.Success) { return("- 您的身份证号码格式有误!"); } cid = cid.ToLower(); cid = cid.Replace("x", "a"); if (int.Parse(cid.Substring(0, 2)) > aCity.Length) { return("- 您的身份证号码格式有误!");//非法地区 } if (aCity[int.Parse(cid.Substring(0, 2))] == null) { return("- 您的身份证号码格式有误!");//非法地区 } try { DateTime.Parse(cid.Substring(6, 2) + "-" + cid.Substring(8, 2) + "-" + cid.Substring(10, 2)); } catch { return("- 您的身份证号码格式有误!");//非法生日 } return(""); }
private string QueryStringMatchEvaluator(System.Text.RegularExpressions.Match match) { try { string url = match.Groups[2].Value; int paramPos = url.IndexOf("?"); if (paramPos != -1) { string parametros = url.Substring(paramPos + 1); if (parametros.Length > 0 && !parametros.StartsWith(_qsName)) { if (parametros.IndexOf("&") != -1) { return(match.Value.Replace(parametros, EncryptQueryString(parametros.Replace("&", "&")))); } else { return(match.Value.Replace(parametros, EncryptQueryString(parametros))); } } } return(match.Value); } catch (Exception) { return(match.Value); } }
public void GetHtml_ReturnsFormFieldAndSetsCookieValueIfDoesNotExist() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.NotNull(cookie); Assert.True(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.True(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.Equal("/", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.Equal(formTokenValue, cookieTokenValue); }
private void OnAnswerResponse(MessageRouter router, Message message, object tag) { if (message.Arguments == "OK") { ((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs()); router.RemoveMessageEvent(message); } else { if (message.Code == "IRO") { Regex.Regex regex = new Regex.Regex( @"(?<userNumber>\d+)\s+(?<totalUsers>\d+)\s+(?<username>\S+)\s+(?<screenName>.*$)" ); Regex.Match match = regex.Match(message.Arguments); if (match.Success) { string username = match.Groups["username"].Value; control.FriendJoin(username); } } } }
List <SheetInfo> GetSpreadSheetIDs(string gDocsUrl) { System.Text.RegularExpressions.Match match = Regex.Match(gDocsUrl, @"(/d/)(.+)/"); string gDocskey = match.Groups[2].Value; string URL = "https://spreadsheets.google.com/spreadsheet/pub?key=" + gDocskey; List <SheetInfo> res = new List <SheetInfo>(); res = GetSheetIDs(URL, res); //Also fetch the ID of the default sheet. if (res.Count > 0) { GetSheetIDs(URL + "&gid=" + res[0].ID, res); } if (res.Count == 0) { Debug.LogWarning("No sheets found, or your spreadsheet has only 1 sheet. We are assuming that the first sheet has ID '0'. (You can fix this by simply adding a second sheet as this will allow ID lookup via HTML output)"); SheetInfo info = new SheetInfo(); info.ID = 0; info.title = "Sheet1"; res.Add(info); } return(res); }
static void Match_Groups(JSVCall vc) { System.Text.RegularExpressions.Match _this = (System.Text.RegularExpressions.Match)vc.csObj; var result = _this.Groups; JSMgr.datax.setObject((int)JSApi.SetType.Rval, result); }
public void GetHtml_SetsCookieDomainAndPathIfSpecified() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context, "some other salt", "theDomain", "thePath").ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.NotNull(cookie); Assert.True(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.Equal("theDomain", cookie.Domain); Assert.Equal("thePath", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.Equal(formTokenValue, cookieTokenValue); }
public static Match[] FindSubstrings(string source, string matchPattern, bool findAllUnique) { SortedList uniqueMatches = new SortedList(); Match[] retArray = null; Regex RE = new Regex(matchPattern, RegexOptions.Multiline); MatchCollection theMatches = RE.Matches(source); if (findAllUnique) { for (int counter = 0; counter < theMatches.Count; counter++) { if (!uniqueMatches.ContainsKey(theMatches[counter].Value)) { uniqueMatches.Add(theMatches[counter].Value, theMatches[counter]); } } retArray = new Match[uniqueMatches.Count]; uniqueMatches.Values.CopyTo(retArray, 0); } else { retArray = new Match[theMatches.Count]; theMatches.CopyTo(retArray, 0); } return (retArray); }
/// <summary> /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 /// </summary> private string ConvertJsonDateToDateString(Match m) { string result = string.Empty; string p = @"\d"; var cArray = m.Value.ToCharArray(); StringBuilder sb = new StringBuilder(); Regex reg = new Regex(p); for (int i = 0; i < cArray.Length; i++) { if (reg.IsMatch(cArray[i].ToString())) { sb.Append(cArray[i]); } } // reg.Replace(m.Value; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(sb.ToString())); dt = dt.ToLocalTime(); result = dt.ToString("yyyy-MM-dd HH:mm:ss"); return result; }
public static string UrlEscaper(Match match) { var url = match.Groups["url"].Value; var processedUrl = string.Format("/proxy?url={0}", Uri.EscapeDataString(url)); return processedUrl; }
public string Files() { System.IO.File.Delete(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan3.txt"); System.IO.File.Delete(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan4.txt"); string readText = System.IO.File.ReadAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan1.txt"); string readText2 = System.IO.File.ReadAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan2.txt"); string[] pattern = { @"(?<=Scanned files: )\d+", @"(?<=Infected files: )\d+", @"(?<=Data read: )\d+.{6}", @"(?<=Time: )\d+.{8}", @".{1,200}FOUND" }; string[] pattern2 = { @"(?<=Wszystkie pliki: )\d+", @"(?<=Pliki zar.{5}: )\d+", @"(?<=Rozmiar: )\d+.{6}", @"(?<=wykonywania: )\d+.{8}", @".{1,200}FOUND" }; string input = readText; string input2 = readText2; for (int i = 0; i < pattern.Length; i++) { // foreach (Match match in Regex.Matches(input, pattern[i])) --> więcej wystąpień System.Text.RegularExpressions.Match x = Regex.Match(input, pattern[i]); System.IO.File.AppendAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan3.txt", "'" + x.Value + "'" + ","); } System.IO.File.AppendAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan3.txt", "'ClamAV'"); for (int i = 0; i < pattern2.Length; i++) { // foreach (Match match in Regex.Matches(input2, pattern2[i])) --> więcej wystąpień System.Text.RegularExpressions.Match x = Regex.Match(input2, pattern2[i]); System.IO.File.AppendAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan4.txt", "'" + x.Value + "'" + ","); } System.IO.File.AppendAllText(@"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan4.txt", "'Avast'"); return((readText) + (readText2)); }
public string Handle(string input, Match match, IListener listener) { var text = match.Groups[1].Value; //test code ToastView.Create(text, "taimur38", false); return text; }
private string ExtractString(Match match) { var name = "?" + _values.Count; var value = RemoveEnds(match.Value.Replace(@"\'", "'")); _values.Add(name, value); return name; }
private static LabelBase Parse(Match match) { if (match == null) { return null; } var labelName = match.Groups["name"].Value; var parameters = match.Groups["parameters"].Value; var label = Factory.GetInstance<LabelBase>(labelName); if (label == null) { return null; } label.TemplateContent = match.Groups[0].Value; label.LabelName = labelName; label.Parameters = LabelParameterParser.Parse(labelName, parameters); var innerContent = match.Groups["inner"].Value; if (string.IsNullOrEmpty(innerContent)) { return label; } label.Fields = FieldParser.Parse(labelName, innerContent); label.InnerLables = Parse(innerContent); return label; }
/// <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); }
public static string ParseIdCard(string _sId) { string[] sArrCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; double nSum = 0; System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x)$"); System.Text.RegularExpressions.Match oMatch = oRegex.Match(_sId); if (!oMatch.Success) { return(""); } _sId = _sId.ToLower(); _sId = _sId.Replace("x", "a"); if (sArrCity[int.Parse(_sId.Substring(0, 2))] == null) { return("非法地区"); } try { DateTime.Parse(_sId.Substring(6, 4) + "-" + _sId.Substring(10, 2) + "-" + _sId.Substring(12, 2)); } catch { return("非法生日"); } for (int i = 17; i >= 0; i--) { nSum += (System.Math.Pow(2, i) % 11) * int.Parse(_sId[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber); } if (nSum % 11 != 1) { return("非法证号"); } return(sArrCity[int.Parse(_sId.Substring(0, 2))] + "," + _sId.Substring(6, 4) + "-" + _sId.Substring(10, 2) + "-" + _sId.Substring(12, 2) + "," + (int.Parse(_sId.Substring(16, 1)) % 2 == 1 ? "男" : "女") ); }
private static System.Text.RegularExpressions.Match FindActionItemPatternInNavigateURL(string selectedLineText) { string pattern = "prioritizeURI:(.*)"; //non greedy regex search (using the ? mark) which search for -AIxxx- matches System.Text.RegularExpressions.Match match = Regex.Match(selectedLineText, pattern); return(match); }
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(); } }
private string ExpandFormattedLinks(System.Text.RegularExpressions.Match M) { //string Href = M.Value; // M.Groups[0].Value; string Text = M.Groups[1].Value; string Href = M.Groups[2].Value; if (Href.IndexOf("://") < 0) { if (Href.StartsWith("www.")) { Href = "http://" + Href; } else if (Href.StartsWith("ftp")) { Href = "ftp://" + Href; } else if (Href.IndexOf("@") > -1) { Href = "mailto:" + Href; } else { Href = "http://" + Href; } } string Targ = !string.IsNullOrEmpty(Target) ? " target='" + Target + "'" : string.Empty; return("<a href='" + Href + "'" + Targ + ">" + Text + "</a>"); }
/// <summary> /// Performs the match. /// </summary> /// <param name="match">The match.</param> /// <returns></returns> protected override string PerformMatch(Match match) { string result = match.Value; result = result.Replace(LEFTBRACE, '('); result = result.Replace(RIGHTBRACE, ')'); return result; }
static void TestRegax() { Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sk.Connect(new IPEndPoint(new IPAddress(new byte[] { 61, 135, 169, 121 }), 80)); string ip = sk.RemoteEndPoint.ToString(); Console.WriteLine(ip.Substring(0, ip.LastIndexOf(':'))); string str; string value = null; using (WebClient wc = new WebClient()) { byte[] b = wc.DownloadData("file:///G:/%E5%AE%A2%E6%88%B7%E8%B5%84%E6%96%99/%E6%BB%A8%E5%B7%9E_%E7%9B%9F%E5%A8%81%E6%88%B4%E5%8D%A1/BCNET%E5%93%8D%E5%BA%94%E5%BC%82%E5%B8%B8%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/bcnet/bcnet/%E8%A5%BF%E9%97%A8%E5%AD%90%E4%BB%A5%E5%A4%AA%E7%BD%91%E9%80%9A%E8%AE%AF%E5%A4%84%E7%90%86%E5%99%A8SCANET-S7.htm"); str = Encoding.GetEncoding("GB2312").GetString(b, 0, b.Length); } System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(str, "<!--#S7ERR-->[0-9]*"); if (m != null && m.Index != -1) { value = m.Value; value = value.Substring(value.LastIndexOf('>') + 1); } Console.WriteLine(value); //WebRequest wr = HttpWebRequest.Create("http://www.baidu.com"); //WebResponse resp = wr.GetResponse(); //resp.GetResponseStream().BeginRead }
/// <summary> /// Regex Match processing delegate to replace the Entities with their /// underlying Unicode character. /// </summary> /// <param name="matchToProcess">Regular Expression Match eg. [ { |  | é ]</param> /// <returns> /// &amp; becomes & (encoded for XML Comments - don't be confused) /// and &eacute; becomes é /// BUT we dont modify the angles or ampersand /// </returns> private static string ResolveEntityNotAngleAmp(System.Text.RegularExpressions.Match matchToProcess) { string x = ""; // default 'char placeholder' if cannot be resolved - shouldn't occur if (matchToProcess.Groups["decimal"].Success) { x = System.Convert.ToChar(System.Convert.ToInt32(matchToProcess.Groups["decimal"].Value)).ToString(); } else if (matchToProcess.Groups["hex"].Success) { x = System.Convert.ToChar(HexToInt(matchToProcess.Groups["hex"].Value)).ToString(); } else if (matchToProcess.Groups["html"].Success) { string entity = matchToProcess.Groups["html"].Value; switch (entity.ToLower()) { case "lt": case "gt": case "amp": x = "&" + entity + ";"; break; default: x = EntityLookup(entity); break; } } else { x = "X"; } return(x); } // ResolveEntityNotAngleAmp()
public void ConstructorTest() { Mock <IIrcWriter> writer = new Mock <IIrcWriter>(MockBehavior.Strict); const string user = "******"; const string channel = "channel"; const string message = "My Message"; Regex regex = new Regex(".+"); System.Text.RegularExpressions.Match match = regex.Match("something"); CtcpPingHandlerArgs uut = new CtcpPingHandlerArgs( writer.Object, user, channel, message, regex, match ); Assert.AreSame(writer.Object, uut.Writer); Assert.AreEqual(user, uut.User); Assert.AreEqual(channel, uut.Channel); Assert.AreEqual(message, uut.Message); Assert.AreSame(regex, uut.Regex); Assert.AreSame(match, uut.Match); }
/* * Aquí va un ejemplo que yo uso para validar el numero de albarán introducido: [AB]([0-9]{9}) * La explicación es la siguiente: * [AB] -> Indica que el primer carácter de la cadena debe ser A o B. En general, con los corchetes indicamos que en esa posición debe aparecer una caracter, pero solo uno, de los que listamos. * ([0-9]{9}) ->Indica que los siguientes nueve caracteres {9} deben ser digitos (del 0 al 9) * Por ejemplo, la expresión sería correcta con: A000001257 ó B000000000, pero fallaria con A1257 o C000001257 */ public static bool ValidaFecha(string fecha) { // string ExpReg = @"(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"; string dia = "(0[1-9]|[12][0-9]|3[01])"; string mes = "(0[1-9]|[1][0-2])"; string anio = "(19|20)[0-9]{2}"; string separador = "[- /.]"; //fecha = "21/12.1999"; string ExpReg = dia + separador + mes + separador + anio; System.Text.RegularExpressions.Match match = Regex.Match(fecha.Trim(), ExpReg, RegexOptions.IgnoreCase); if (match.Success) { return(true); } else { return(false); } }