public static void ReplaceTarget(List<string> words) { using (StreamReader reader = new StreamReader("test.txt")) { using (StreamWriter writer = new StreamWriter("temp.txt")) { StringBuilder sb = new StringBuilder(); sb.Append(@"\b("); foreach (string word in words) sb.Append(word + "|"); sb.Remove(sb.Length - 1, 1); sb.Append(@")\b"); string pattern = @sb.ToString(); Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); for (string line; (line = reader.ReadLine()) != null; ) { string newLine = rgx.Replace(line, ""); writer.WriteLine(newLine); } } } File.Delete("test.txt"); File.Move("temp.txt", "test.txt"); }
public static void Main() { var instructions = new List<Instruction>(); var regex = new Regex(@"(?:cpy ([a-d]) ([a-d])|cpy (\d+) ([a-d])|inc ([a-d])|dec ([a-d])|jnz ([a-d]) (-?\d+)|jnz (\d+) (\d+))"); string line; while ((line = Console.ReadLine()) != null) { Match match = regex.Match(line); if (match.Groups[1].Success) { instructions.Add(new CpyRegInstruction(match.Groups[1].Value[0] - 'a', match.Groups[2].Value[0] - 'a')); } else if (match.Groups[3].Success) { instructions.Add(new CpyValInstruction(int.Parse(match.Groups[3].Value), match.Groups[4].Value[0] - 'a')); } else if (match.Groups[5].Success) { instructions.Add(new AddInstruction(match.Groups[5].Value[0] - 'a', 1)); } else if (match.Groups[6].Success) { instructions.Add(new AddInstruction(match.Groups[6].Value[0] - 'a', -1)); } else if (match.Groups[7].Success) { instructions.Add(new JnzInstruction(match.Groups[7].Value[0] - 'a', int.Parse(match.Groups[8].Value))); } else if (match.Groups[9].Success) { instructions.Add(new JmpInstruction(int.Parse(match.Groups[9].Value) == 0 ? 1 : int.Parse(match.Groups[10].Value))); } else { Console.WriteLine("Failed to parse instruction: " + line); } } int pc = 0; var registers = new int[4]; registers[2] = 1; while (pc < instructions.Count) { pc += instructions[pc].Run(registers); } Console.WriteLine($"pc: {pc}, a: {registers[0]}, b: {registers[1]}, c: {registers[2]}, d: {registers[3]}" ); }
static void Main() { string input = Console.ReadLine(); var validUsernames = new List<string>(); string pattern = @"[\w\d]{2,24}"; Regex rgx = new Regex(pattern); MatchCollection matches = rgx.Matches(input); foreach (var match in matches) { if (char.IsLetter(match.ToString().First())) { validUsernames.Add(match.ToString()); } } int sum = 0; int index = 0; for (int i = 0; i < validUsernames.Count-1; i++) { int currentSum = validUsernames[i].Length + validUsernames[i + 1].Length; if (currentSum > sum) { sum = currentSum; index = i; } } Console.WriteLine(validUsernames[index]); Console.WriteLine(validUsernames[index+1]); }
static void Main(string[] args) { string email = "I was born at 14.06.1980. My sister was born at 3.7.1984. In 5/1999 I graduated my high school. The law says (see section 7.3.12) that we are allowed to do this (section 7.4.2.9)."; int startIndex = -1; int EndIndex = 0; Regex regex = new Regex(@"^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"); do { EndIndex = email.IndexOf(" ", startIndex + 1); if (EndIndex > 0) { string word = email.Substring(startIndex + 1, EndIndex - startIndex - 1); if (word[word.Length - 1] == '.') { word = (word.Substring(0, word.Length - 1)); } if (regex.IsMatch(word)) { Console.WriteLine(word); } startIndex = EndIndex; } } while (EndIndex > 0); }
static void Main(string[] args) { using (StreamReader reader = File.OpenText(args[0])) while (!reader.EndOfStream) { string[] line = reader.ReadLine().Split(','); Regex regex = new Regex(@"[0-9]+"); List<string> words = new List<string>(); List<string> numbers = new List<string>(); for (int i = 0; i < line.Length; i++) { if (regex.IsMatch(line[i])) numbers.Add(line[i]); else words.Add(line[i]); } string left = string.Join(",", words.ToArray<string>()); string right = string.Join(",", numbers.ToArray<string>()); if (string.IsNullOrEmpty(left)) Console.WriteLine(right); else if (string.IsNullOrEmpty(right)) Console.WriteLine(left); else Console.WriteLine(left + "|" + right); } }
public static void RegexSplit() { string[] saExp = new string[] { "kkk", "lll", "mmm", "nnn", "ooo" }; string[] saExp1 = new string[] { "kkk", "lll:mmm:nnn:ooo" }; string[] saExp2 = new string[] { "kkk:lll", "mmm", "nnn:ooo" }; string input = "kkk:lll:mmm:nnn:ooo"; Regex regex = new Regex(":"); // Split(string) string[] result = regex.Split(input); Assert.Equal(saExp, result); // A count of 0 means split all result = regex.Split(input, 0); Assert.Equal(saExp, result); // public static String[] Split(string input, Int32 count); ":" // "kkk:lll:mmm:nnn:ooo", 2 result = regex.Split(input, 2); Assert.Equal(saExp1, result); // public static String[] Split(string input, Int32 count, Int32 startat); ":" // "kkk:lll:mmm:nnn:ooo", 3, 6 result = regex.Split(input, 3, 6); Assert.Equal(saExp2, result); }
//Write a program that reads a list of words from a file words.txt and finds how many times //each of the words is contained in another file test.txt. The result should be written in //the file result.txt and the words should be sorted by the number of their occurrences in //descending order. Handle all possible exceptions in your methods. private static Dictionary<string, int> CountWords(string inputPath, string listOfWordsPath) { List<string> list = ExtractList(listOfWordsPath); StreamReader reader = new StreamReader(inputPath); Dictionary<string, int> result = new Dictionary<string, int>(); using (reader) { while (reader.Peek() != -1) { string currline = reader.ReadLine(); for (int i = 0; i < list.Count; i++) { Regex word = new Regex("\\b" + list[i] + "\\b"); foreach (Match match in word.Matches(currline)) { //for each word met, if already met - increase counter, else - start counting it if (result.ContainsKey(list[i])) { result[list[i]]++; } else { result.Add(list[i], 1); } } } } } return result; }
public static Path3D LoadPaths(string fileName) { try { string input = File.ReadAllText(fileName); string pattern = @"X=(.+?), Y=(.+?), Z=(.+?)"; var reg = new Regex(pattern); var matchs = reg.Matches(input); Path3D path = new Path3D(); foreach (Match match in matchs) { double x = double.Parse(match.Groups[1].Value); double y = double.Parse(match.Groups[2].Value); double z = double.Parse(match.Groups[3].Value); Point3D point = new Point3D(x, y, z); path.AddPoint(point); } return path; } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex.InnerException; } }
/// <summary> /// /// </summary> /// <param name="String"></param> /// <param name="RegexString"></param> /// <returns></returns> public static GroupCollection RegexMatch(this String String, string RegexString) { var Regex = new Regex(RegexString, RegexOptions.None); var Match = Regex.Match(String); if (Match == Match.Empty) return null; return Match.Groups; }
public static Path LoadPathOfFile(string fileName) { Path path = new Path(); using (StreamReader sr = new StreamReader(fileName)) { string input = sr.ReadToEnd(); string pattern = "{([\\d,.]+), ([\\d,.]+), ([\\d,.]+)}"; var reg = new Regex(pattern); var matchs = reg.Matches(input); if (matchs.Count <= 0) { throw new ApplicationException("Invalid data in file " + fileName); } foreach (Match match in matchs) { double x = double.Parse(match.Groups[1].Value); double y = double.Parse(match.Groups[2].Value); double z = double.Parse(match.Groups[3].Value); Point p = new Point(x, y, z); path.AddPoint(p); } } return path; }
static void Main() { StringBuilder line = new StringBuilder(); string pattern = @"(?<![a-zA-Z])[A-Z]+(?![a-zA-Z])"; Regex regex = new Regex(pattern); while (line.ToString() != "END") { MatchCollection matches = regex.Matches(line.ToString()); int offset = 0; foreach (Match match in matches) { string word = match.Value; string reversed = Reverse(word); if (reversed == word) { reversed = DoubleEachLetter(reversed); } int index = match.Index; line = line.Remove(index + offset, word.Length); line = line.Insert(index + offset, reversed); offset += reversed.Length - word.Length; } Console.WriteLine(SecurityElement.Escape(line.ToString())); line = new StringBuilder(Console.ReadLine()); } }
//public void LoadLeft(string name_en_s) //{ // data_conn cn = new data_conn(); // if (name_en_s != "") // { // DataSet ds = cn.mdb_ds("select top 5 * from TB_BBS where title like '%" + name_en_s + "%'", "bbs"); // Repeater1.DataSource = ds.Tables["bbs"].DefaultView; // Repeater1.DataBind(); // string strYear = DateTime.Now.Year.ToString(); // string strMonth = DateTime.Now.Month.ToString(); // DataSet ds = cn.mdb_ds("select top 1 * from TB_BAF where months='" + strYear + "-" + strMonth + "' and Carriers like '%" + name_en_s + "%'", "baf"); // if (ds.Tables["baf"].Rows.Count > 0) // { // Literal8.Text = "<a href='../baf/#anchor" + ds.Tables["baf"].Rows[0]["id"].ToString() + "'>" + strMonth + "月" + name_en_s + "最新BAF/CAF</a><br />"; // } // ds = cn.mdb_ds("select top 1 * from TB_THC where months='" + strYear + "-" + strMonth + "' and Carriers='" + name_en_s + "'", "thc"); // if (ds.Tables["thc"].Rows.Count > 0) // { // Literal9.Text = "<a href='../thc/#anchor" + ds.Tables["thc"].Rows[0]["id"].ToString() + "'>" + strMonth + "月" + name_en_s + "最新THC</a><br />"; // } // ds = cn.mdb_ds("select top 5 * from TB_Search_Ship order by Num desc", "hot"); // Repeater2.DataSource = ds.Tables["hot"].DefaultView; // Repeater2.DataBind(); // } //} public string GetFirstString(string stringToSub,int length) { Regex regex=new Regex("[\u4e00-\u9fa5\uff00-\uffef\u3000-\u303f\u2000-\u206f\u25a0-\u25ff]+", RegexOptions.Compiled); char[] stringChar = stringToSub.ToCharArray(); StringBuilder sb = new StringBuilder(); int nLength = 0; bool isCut = false; for (int i = 0; i < stringChar.Length; i++) { if (regex.IsMatch((stringChar[i]).ToString())) { sb.Append(stringChar[i]); nLength += 2; } else { sb.Append(stringChar[i]); nLength = nLength + 1; } if(nLength >length ) { isCut = true; break; } } return sb.ToString(); }
static void Main(string[] args) { string text = Console.ReadLine(); string pattern = (@"(.)\1+"); Regex regex = new Regex(pattern); Console.WriteLine(regex.Replace(text, "$1")); }
static void Main() { Regex pairMatcher = new Regex(@"(\D+)(\d+)"); string input = Console.ReadLine(); Match pair = pairMatcher.Match(input); StringBuilder result = new StringBuilder(); do { string str = pair.Groups[1].Value.ToUpper(); int count = int.Parse(pair.Groups[2].Value); for (int i = 0; i < count; i++) { result.Append(str); } pair = pair.NextMatch(); } while (pair.Success); int uniqueSymbols = result.ToString().Distinct().Count(); Console.WriteLine("Unique symbols used: {0}", uniqueSymbols); Console.WriteLine(result); }
static void Main() { const string Keys = @"(?<startKey>^[A-Za-z_]*)(?=\d).*(?<=\d)(?<endKey>[A-Za-z_]*)"; var keysMatcher = new Regex(Keys); string keysString = Console.ReadLine(); string startKey = keysMatcher.Match(keysString).Groups["startKey"].Value; string endKey = keysMatcher.Match(keysString).Groups["endKey"].Value; if (string.IsNullOrEmpty(startKey) || string.IsNullOrEmpty(endKey)) { Console.WriteLine("<p>A key is missing</p>"); return; } string Pattern = string.Format("(?:{0}){1}(?:{2})", startKey, @"(\d*\.?\d+)", endKey); var numbersMatcher = new Regex(Pattern); string textString = Console.ReadLine(); var matches = numbersMatcher.Matches(textString); var numbers = (from Match number in matches select double.Parse(number.Groups[1].Value)).ToList(); if (numbers.Count == 0) { Console.WriteLine("<p>The total value is: <em>nothing</em></p>"); } else { double sum = numbers.Sum(); Console.WriteLine("<p>The total value is: <em>{0}</em></p>",sum); } }
private static void DeletesText(string firstFileName, string word) { //deleting text using regular expresions //first we read and save the word into List List<string> nonDeleteText = new List<string>(); StreamReader reader = new StreamReader(firstFileName); using (reader) { string line = reader.ReadLine(); //the only diffrence is the regular expresion below string pattern = @"\b(" + String.Join("|", File.ReadAllLines("../../words.txt")) + @")\b"; while (line != null) { Regex rgx = new Regex(pattern); line = rgx.Replace(line, ""); nonDeleteText.Add(line); line = reader.ReadLine(); } } //secondly we are writting the saved List back to the file StreamWriter writer = new StreamWriter(firstFileName); using (writer) { for (int i = 0; i < nonDeleteText.Count; i++) { writer.WriteLine(nonDeleteText[i]); } } }
static void Main(string[] args) { // Search the input for the specified patter, which is {letter}{some digits}{letter} string pattern = @"[a-zA-Z]\d+[a-zA-Z]"; Regex regex = new Regex(pattern); MatchCollection matches = Regex.Matches(Console.ReadLine(), @"[a-zA-Z]\d+[a-zA-Z]"); // Fill in a list with all entries matching the pattern List<string> entries = new List<string>(); foreach (Match match in matches) { entries.Add(match.ToString()); } // Get the sum of all entries double sum = 0d; foreach (string entry in entries) { sum += CalculateEntryValue(entry); } // Print the sum Console.WriteLine("{0:F2}", sum); }
private bool isFieldValid(List<object> fieldTypeValue) { Regex regEx; string fieldValue = (string)fieldTypeValue[2]; switch ((FieldType)fieldTypeValue[1]) { case FieldType.Integer: regEx = new Regex(@"^\d+$"); return regEx.IsMatch(fieldValue); break; case FieldType.Phone: regEx = new Regex(@"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"); return regEx.IsMatch(fieldValue); break; case FieldType.Email: regEx = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); return regEx.IsMatch(fieldValue); break; case FieldType.URL: regEx = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); return regEx.IsMatch(fieldValue); break; case FieldType.SSN: regEx = new Regex(@"^\d{3}-\d{2}-\d{4}$"); return regEx.IsMatch(fieldValue); break; case FieldType.NonEmptyString: return fieldValue.Trim().Length > 0; break; } return true; }
public int GetWorth() { Regex regex = new Regex (@"\d+"); Match match = regex.Match (gameObject.name); int worth = int.Parse (match.Value); return worth; }
/// <summary> /// Rewrites the URL and redirect the request to destination page from rules in web.config /// </summary> public static void RewriteUrl() { RewriteConfigurationSection config = (RewriteConfigurationSection)ConfigurationManager.GetSection("rewrite"); if (config != null) { if (config.Rules != null) { foreach (RewriteRuleElement rule in config.Rules) { Regex r = new Regex(rule.Url, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); Match m = r.Match(HttpContext.Current.Request.Url.AbsolutePath); if (m.Success) { string destinationUrl = rule.Destination; for (int i = 0; i < m.Groups.Count; i++) { if (m.Groups[i].Index > 0) destinationUrl = destinationUrl.Replace("$" + i.ToString(), m.Groups[i].Value); } RewriteContext ctx = new RewriteContext(); ctx.RewritedUrl = HttpContext.Current.Request.Url.AbsoluteUri; HttpContext.Current.Items.Add("REWRITECONTEXT", ctx); HttpContext.Current.RewritePath(destinationUrl + HttpContext.Current.Request.Url.Query); } } } else throw new Exception("Cannot find <rules> node in web.config"); } else throw new Exception("Cannot find <rewrite> node in web.config"); }
static void Main() { int n = int.Parse(Console.ReadLine()); string concatenated = ""; for (int i = 0; i < n; i++) { int number = int.Parse(Console.ReadLine()); concatenated += Convert.ToString(number, 2).PadLeft(32, '0').Substring(2, 30);//TODO use stringbuilder } //Console.WriteLine(concatenated); Regex reg1 = new Regex(@"(1)\1+"); MatchCollection matches = reg1.Matches(concatenated); int longest1 = 0; foreach (System.Text.RegularExpressions.Match match in matches) { if (longest1 < match.Length) longest1 = match.Length; } Console.WriteLine(longest1); Regex reg2 = new Regex(@"(0)\1+"); MatchCollection matches2 = reg2.Matches(concatenated); int longest2 = 0; foreach (System.Text.RegularExpressions.Match match in matches2) { if (longest2 < match.Length) longest2 = match.Length; } Console.WriteLine(longest2); }
public static void Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException() { Regex regex = new Regex("e"); MatchCollection matches = regex.Matches("dotnet"); Assert.Throws<ArgumentOutOfRangeException>("i", () => matches[-1]); Assert.Throws<ArgumentOutOfRangeException>("i", () => matches[matches.Count]); }
static void ReplaceLinkTags(ref string html) { string pattern = @"<a\s+href=\""(.+)\"">(.+)<\/a>"; var regex = new Regex(pattern); html = regex.Replace(html, "[URL href=$1]$2[/URL]"); }
static void Main() { string input = Console.ReadLine(); string pattern = @"<a\s+href=([^>]+)>([^<]+)</a>"; Regex regex = new Regex(pattern); string replacement = "[URL href=$1]$2[/URL]"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result); //Console.WriteLine("Enter HTML document"); //string textHTML = Console.ReadLine(); //string output = string.Empty; //int counter = 0; //while (textHTML.IndexOf("<a href=\"", counter) > 0) //{ // output = textHTML.Replace("<a href=\"", "[URL="); // counter++; //} //counter = 0; //while (output.IndexOf("\">", counter) > 0) //{ // output = output.Replace("\">", "]"); // counter++; //} //counter = 0; //while (output.IndexOf("</a>", counter) > 0) //{ // output = output.Replace("</a>", "[/URL]"); // counter++; //} //Console.WriteLine(output); }
public static void Main() { while (true) { string[] input = Console.ReadLine().Split(' '); if (input[0] == "END") { break; } for (int i = 0; i < input.Length; i++) { string pattern = @"\b(?:\d*|\W*)([A-Z]{1,})(?:\d*|\W*)\b"; Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(input[i]); foreach (Match match in matches) { string oldString = match.Groups[1].ToString(); string reverse = new string(oldString.Reverse().ToArray()); if (match.Groups[1].Length == 1 || oldString.Equals(reverse)) { string newString = ReplaceWithDoubleLetters(oldString); input[i] = input[i].Replace(oldString, newString); } else { input[i] = input[i].Replace(oldString, reverse); } } } Console.WriteLine(SecurityElement.Escape(string.Join(" ", input))); } }
private static MatchCollection IsSentence(string text) { string pattern = @"([^.!?]+(?=[.!?])[.!?])"; Regex rgx = new Regex(pattern); MatchCollection matches = rgx.Matches(text); return matches; }
public TcmUri(string Uri) { Regex re = new Regex(@"tcm:(\d+)-(\d+)-?(\d*)-?v?(\d*)"); Match m = re.Match(Uri); if (m.Success) { PublicationId = Convert.ToInt32(m.Groups[1].Value); ItemId = Convert.ToInt32(m.Groups[2].Value); if (m.Groups.Count > 3 && !string.IsNullOrEmpty(m.Groups[3].Value)) { ItemTypeId = Convert.ToInt32(m.Groups[3].Value); } else { ItemTypeId = 16; } if (m.Groups.Count > 4 && !string.IsNullOrEmpty(m.Groups[4].Value)) { Version = Convert.ToInt32(m.Groups[4].Value); } else { Version = 0; } } }
public static SqlChars RegexGroup( SqlChars input, SqlString pattern, SqlString name ) { Regex regex = new Regex( pattern.Value, Options ); Match match = regex.Match( new string( input.Value ) ); return match.Success ? new SqlChars( match.Groups[name.Value].Value ) : SqlChars.Null; }
public static bool IsIPAddress(string str1) { if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false; string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$"; Regex regex = new Regex(regformat, RegexOptions.IgnoreCase); return regex.IsMatch(str1); }
/// <summary> /// 验输入字符串是否含有“/\:.?*|$]”特殊字符 /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsSpecialChar(this string source) { Regex r = new Regex(@"[/\<>:.?*|$]"); return r.IsMatch(source); }
/// <summary> /// 是否包含双字节字符(允许有单字节字符) /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsDoubleChar(this string source) { return Regex.IsMatch(source, @"[^\x00-\xff]"); }
/// <summary> /// 判断是否是中国邮政编码 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsZipCode(this string input) { Regex reg = new Regex(@"^([\d]{6})$"); return reg.IsMatch(input); }
/// <summary> /// 是否是手机号码 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsMobilPhone(this string input) { Regex reg = new Regex(@"^([\d]{11})$"); return reg.IsMatch(input); }
/// <summary> /// 是否是32位MD5 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsMD5(this string input) { Regex reg = new Regex(@"^([\w\d]{32})$"); return reg.IsMatch(input); }
/// <summary> /// 判断是否是合法的QQ号码 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsQQ(this string input) { Regex reg = new Regex(@"^([1-9][0-9]{4,10})$"); return reg.IsMatch(input); }
/// <summary> /// 是否为文件物理路径 /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsPhysicalPath(this string source) { return Regex.IsMatch(source, @"^[a-zA-Z]:[\\/]+(?:[^\<\>\/\\\|\:""\*\?\r\n]+[\\/]+)*[^\<\>\/\\\|\:""\*\?\r\n]*$"); }
/// <summary> /// 是否为日期+时间型字符串 /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsDateTime(this string source) { return Regex.IsMatch(source, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$"); }
/// <summary> /// 是否为时间型字符串 /// </summary> /// <param name="source">时间字符串(15:00:00)</param> /// <returns></returns> public static bool IsTime(this string source) { return Regex.IsMatch(source, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$"); }
/// <summary> /// 判断是否公网IP /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsPublicIP(this string source) { return Regex.IsMatch(source, @"^(((25[0-5]|2[0-4][0-9]|19[0-1]|19[3-9]|18[0-9]|17[0-1]|17[3-9]|1[0-6][0-9]|1[1-9]|[2-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]))|(192\.(25[0-5]|2[0-4][0-9]|16[0-7]|169|1[0-5][0-9]|1[7-9][0-9]|[1-9][0-9]|[0-9]))|(172\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|1[0-5]|3[2-9]|[4-9][0-9]|[0-9])))\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$"); }
/// <summary> /// 是否全为中文/日文/韩文字符 /// </summary> /// <param name="source">源字符串</param> /// <returns></returns> public static bool IsChineseChar(this string source) { //中文/日文/韩文: [\u4E00-\u9FA5] //英文:[a-zA-Z] return Regex.IsMatch(source, @"^[\u4E00-\u9FA5]+$"); }
/// <summary> /// 请求模块 /// </summary> /// <param name="context"></param> private static Task RequestModule(ICompatibleHttpContext context) { // // 参数: // module:模块 // action:动作 // //触发事件 OnManageRequest?.Invoke(context); //获取请求和发送对象 var request = context.Request; var response = context.Response; //不需要进行权限验证的页面 var query = context.Request.GetQueryString(); if (Regex.IsMatch(query, "^\\?res=[^&]+")) { return CallMethod(context, typeof(ResourceHandler), "Read"); } else { if (Regex.IsMatch(query, "^\\?res_combine=[^&]+")) { return CallMethod(context, typeof(ResourceHandler), "Combine"); } //加载页面 if (Regex.IsMatch(query, "^\\?load=(.+?)")) { return CallMethod(context, typeof(SystemHandler), "Load"); } if (query.StartsWith("?ls", true, CultureInfo.InvariantCulture)) { return CallMethod(context, typeof(SystemHandler), "LoadSession"); } } //获取模块和动作参数 var module = request.Query("module"); var action = request.Query("action"); if (string.IsNullOrEmpty(action)) action = "Index"; //检测是否已经登录并检验是否有权执行此操作 if (Regex.IsMatch(action, "^(?!login|verifycode)[a-z]*$", RegexOptions.IgnoreCase)) { //UserState.Administrator.Login("admin", "123000", 1000); // // context.Session["$jr.ASK"] = new UserDto // { // Id = 1, // IsMaster =true, // Name = "管理员" // }; if (!UserState.Administrator.HasLogin) { //response.Redirect(String.Format("{0}?action=login",request.Path), true); return response.WriteAsync( $"<script>window.parent.location.replace('{request.GetPath()}?action=login')</script>"); } // 无权执行操作则返回 if (!HasPermissions()) return SafetyTask.CompletedTask; } // 默认返回system的界面 if (String.IsNullOrEmpty(module)) { return CallMethod(context, typeof(SystemHandler), action); } // 检验参数的合法性 switch (module) { //主页 case "system":return CallMethod(context, typeof(SystemHandler), action); //站点管理 case "site":return CallMethod(context, typeof(SiteHandler), action); //AJAX操作 case "ajax":return CallMethod(context, typeof(AjaxHandler), action); //文档 case "archive":return CallMethod(context, typeof(ArchiveHandler), action); //栏目 case "category":return CallMethod(context, typeof(CategoryHandler), action); //链接 case "link":return CallMethod(context, typeof(LinkHandler), action); //用户 case "user":return CallMethod(context, typeof(UserHandler), action); //模板 case "template":return CallMethod(context, typeof(TemplateHandler), action); //插件 case "plugin":return CallMethod(context, typeof(PluginHandler), action); //图像 case "file":return CallMethod(context, typeof(FileHandler), action); //上传 case "upload":return CallMethod(context, typeof(UploadHandler), action); //模块 // case "module": // return CallMethod(context, typeof(ModuleHandler), action); //表单 case "table":return CallMethod(context, typeof(TableHandler), action); //工具 // case "tool": // return CallMethod(context, typeof(MToolsHandler), action); //扩展字段 case "extend":return CallMethod(context, typeof(ExtendHandler), action); // 助手 case "assistant":return CallMethod(context, typeof(AssistantHandler), action); // 编辑器 case "editor":return CallMethod(context, typeof(EditorHandler), action); } return context.Response.WriteAsync("模块错误,请检查!"); }
/// <summary> /// 验证IP /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsIP(this string source) { return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$"); }
public void SkipSpace() { var fl = FetchLine(); var m = Regex.Match(fl,@"\s+"); StepCount(m.Length); }
/// <summary> /// Email 格式是否合法 /// </summary> /// <param name="source"></param> public static bool IsEmail(this string source) { return Regex.IsMatch(source, @"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$"); }
private string ReadName(string fl) { var m = Regex.Match(fl, @"[a-zA-Z0-9_]+"); StepCount(m.Length); return m.Value; }
public bool TryQuery(out FulltextSearchResult result, string query) { var regexpression = new Regex(query, RegexOptions.IgnoreCase); var foundSth = false; result = null; if (ReadResource()) { try { var matchingGraphElements = new Dictionary <AGraphElement, NestedHighLightAndCounter>(); var currentScore = 0; var maximumScore = 0; const char whitespace = ' '; foreach (var aKV in _idx) { var matches = regexpression.Matches(aKV.Key); if (matches.Count > 0) { if (!foundSth) { result = new FulltextSearchResult(); foundSth = true; } var localHighlights = new HashSet <String>(); var countOfLocalHighlights = 0; foreach (Match match in matches) { var currentPosition = -1; var lastPosition = -1; for (var i = 0; i < match.Index; i++) { if (aKV.Key[i] == whitespace) { currentPosition = i; } if (currentPosition > lastPosition) { lastPosition = currentPosition; } } var firstWhitespacePrev = lastPosition; lastPosition = -1; for (var i = match.Index + match.Length; i < aKV.Key.Length; i++) { if (aKV.Key[i] == whitespace) { lastPosition = i; break; } } var firstWhitespaceAfter = lastPosition; if (firstWhitespacePrev == -1 && firstWhitespaceAfter == -1) { localHighlights.Add(aKV.Key); countOfLocalHighlights++; continue; } if (firstWhitespacePrev == -1) { localHighlights.Add(aKV.Key.Substring(0, firstWhitespaceAfter)); countOfLocalHighlights++; continue; } if (firstWhitespaceAfter == -1) { localHighlights.Add(aKV.Key.Substring(firstWhitespacePrev + 1)); countOfLocalHighlights++; continue; } localHighlights.Add(aKV.Key.Substring(firstWhitespacePrev + 1, firstWhitespaceAfter - firstWhitespacePrev - 1)); countOfLocalHighlights++; } for (var i = 0; i < aKV.Value.Count; i++) { NestedHighLightAndCounter globalHighlights; if (matchingGraphElements.TryGetValue(aKV.Value[i], out globalHighlights)) { globalHighlights.Highlights.UnionWith(localHighlights); currentScore = globalHighlights.NumberOfHighlights + countOfLocalHighlights; } else { matchingGraphElements.Add(aKV.Value[i], new NestedHighLightAndCounter { Highlights = new HashSet <string>(localHighlights), NumberOfHighlights = countOfLocalHighlights }); currentScore = countOfLocalHighlights; } maximumScore = currentScore > maximumScore ? currentScore : maximumScore; } } } if (foundSth) { //create the result result = new FulltextSearchResult { MaximumScore = maximumScore, Elements = matchingGraphElements .Select(aKV => new FulltextSearchResultElement(aKV.Key, aKV.Value.NumberOfHighlights, aKV.Value.Highlights)) .ToList() }; } return(foundSth); } finally { FinishReadResource(); } } throw new CollisionException(this); }
public async Task<string> FileDownloadAsync(string url) { HttpClient client = new HttpClient(handler, false); client.DefaultRequestHeaders.Add("user-agent", userAgent); client.DefaultRequestHeaders.Add("referer", url); var res = await client.GetAsync(url); res.EnsureSuccessStatusCode(); var html = await res.Content.ReadAsStringAsync(); string p = @"<iframe.*?name=""\d{5,}"".*?src=""(.*?)"""; var src = Regex.Match(html, p).Groups[1].Value; Uri u = new Uri(url); var hostbase = u.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped); var frame = hostbase + src; res = await client.GetAsync(frame); res.EnsureSuccessStatusCode(); html = await res.Content.ReadAsStringAsync(); /* var cgcroc = 'UDYHOV1sBzZUXQs0CjoHO1c_aV2UEYgA0Cj9bZFM6Bz8JL1V2D29UMQFiA2wHZFVnA2ADNwVtBzwDPA_c_c';//var harse = 'ate'; var pposturl = '?v2';//var harse = harse;var cess = cess; //var ajaxup = ''; $.ajax({ type : 'post', url : '/ajaxm.php', //data : { 'action':'downprocess','sign':pposturl,'ves':1 }, data : { 'action':'downprocess','sign':cgcroc,'ves':1 }, */ var mc = Regex.Match(html, @"var cgcroc = '(.+?)'"); //var json = mc.Groups[1].Value.Replace("'", "\""); //JsonDocument json1 = JsonDocument.Parse(json); //var ps = json1.RootElement.EnumerateObject().Select(x => new KeyValuePair<string, string>(x.Name, x.Value.ToString())); Dictionary<string, string> ps = new Dictionary<string, string>(5) { { "action","downprocess"}, { "sign",mc.Groups[1].Value}, { "ves","1"}, }; FormUrlEncodedContent encodedContent = new FormUrlEncodedContent(ps); //var postContent = new StringContent(json, Encoding.UTF8, "application/json"); var linkUrl = hostbase + "/ajaxm.php"; res = await client.PostAsync(linkUrl, encodedContent); res.EnsureSuccessStatusCode(); html = await res.Content.ReadAsStringAsync(); var linkinfo = System.Text.Json.JsonSerializer.Deserialize<GetLinkResponse>(html); if (!linkinfo.zt.HasValue || linkinfo.zt.Value != 1) throw new Exception("获取直链失败,状态码:" + html); res = await client.GetAsync(linkinfo.FullUrl); res.EnsureSuccessStatusCode(); html = await res.Content.ReadAsStringAsync(); if (html.Contains("网络异常")) { System.Threading.Thread.Sleep(2000);//need keep this client.DefaultRequestHeaders.Remove("referer"); client.DefaultRequestHeaders.Add("referer", linkinfo.FullUrl); client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest"); //需要二次验证 var file_token = Regex.Match(html, @"'file':'(.+?)'").Groups[1].Value; var file_sign = Regex.Match(html, @"'sign':'(.+?)'").Groups[1].Value; var check_api = linkinfo.dom + "/file/ajax.php"; var dic = new Dictionary<string, string>(3); dic.Add("file", file_token); dic.Add("sign", file_sign); dic.Add("el", "2"); encodedContent = new FormUrlEncodedContent(dic); var c = new StringContent($"file_token={file_token}&file_sign={file_sign}&el=2", Encoding.UTF8, "application/x-www-form-urlencoded"); res = await client.PostAsync(check_api, encodedContent); res.EnsureSuccessStatusCode(); var resJson = await res.Content.ReadAsStringAsync(); var jd = System.Text.Json.JsonDocument.Parse(resJson); var aurl = jd.RootElement.GetProperty("url").GetString(); client.Dispose(); return aurl; } else { client.Dispose(); //重定向后的真直链 return res.Content.Headers.ContentLocation.ToString(); } }
private string ReadQuote(string fl) { var m = Regex.Match(fl, @"""(\\""|[^""])+"""); if (!m.Success) return null; StepCount(m.Length); return TrimedQuoteText(m.Value); }
/// <summary> /// Gets regex fragment matching single folder name. /// </summary> /// <remarks> /// Zero or more acceptable characters will match the /// pattern. This pattern will not permit directory /// separators. /// </remarks> private string GetWildCardRegexPatternForFolderName() { string invalidCharacters = InvalidPathCharacters + DirectorySeparators; return string.Concat("[^", Regex.Escape(invalidCharacters), "]*"); }
int GetInteger(string str) { str = Regex.Replace(str, @"[^0-9]+", ""); return int.Parse(str); }
/// <summary> /// Gets regex fragment matching acceptable file names. /// </summary> /// <remarks> /// At least one character is required to successfully /// match the pattern. /// </remarks> private string GetAcceptableCharacterRange() { return string.Concat("[^", Regex.Escape(InvalidPathCharacters), "]+"); }
public void SubmitsTraces(string packageVersion) { var expectedSpanCount = 26; int basicPublishCount = 0; int basicGetCount = 0; int basicDeliverCount = 0; int exchangeDeclareCount = 0; int queueDeclareCount = 0; int queueBindCount = 0; var distributedParentSpans = new Dictionary<ulong, int>(); int emptyBasicGetCount = 0; int agentPort = TcpPortProvider.GetOpenPort(); using (var agent = new MockTracerAgent(agentPort)) using (var processResult = RunSampleAndWaitForExit(agent.Port, packageVersion: packageVersion)) { Assert.True(processResult.ExitCode >= 0, $"Process exited with code {processResult.ExitCode} and exception: {processResult.StandardError}"); var spans = agent.WaitForSpans(expectedSpanCount); // Do not filter on operation name because they will vary depending on instrumented method Assert.True(spans.Count >= expectedSpanCount, $"Expecting at least {expectedSpanCount} spans, only received {spans.Count}"); var rabbitmqSpans = spans.Where(span => string.Equals(span.Service, ExpectedServiceName, StringComparison.OrdinalIgnoreCase)); var manualSpans = spans.Where(span => !string.Equals(span.Service, ExpectedServiceName, StringComparison.OrdinalIgnoreCase)); foreach (var span in rabbitmqSpans) { Assert.Equal(SpanTypes.Queue, span.Type); Assert.Equal("RabbitMQ", span.Tags[Tags.InstrumentationName]); Assert.False(span.Tags?.ContainsKey(Tags.Version), "External service span should not have service version tag."); Assert.NotNull(span.Tags[Tags.AmqpCommand]); Assert.Equal("amqp.command", span.Name); var command = span.Tags[Tags.AmqpCommand]; if (command.StartsWith("basic.", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(command, "basic.publish", StringComparison.OrdinalIgnoreCase)) { basicPublishCount++; Assert.Equal(SpanKinds.Producer, span.Tags[Tags.SpanKind]); Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); Assert.NotNull(span.Tags["message.size"]); Assert.True(int.TryParse(span.Tags["message.size"], out _)); // Enforce that the resource name has the following structure: "basic.publish [<default>|{actual exchangeName}] -> [<all>|<generated>|{actual routingKey}]" string regexPattern = @"basic\.publish (?<exchangeName>\S*) -> (?<routingKey>\S*)"; var match = Regex.Match(span.Resource, regexPattern); Assert.True(match.Success); var exchangeName = match.Groups["exchangeName"].Value; Assert.True(string.Equals(exchangeName, "<default>") || string.Equals(exchangeName, span.Tags[Tags.AmqpExchange])); var routingKey = match.Groups["routingKey"].Value; Assert.True(string.Equals(routingKey, "<all>") || string.Equals(routingKey, "<generated>") || string.Equals(routingKey, span.Tags[Tags.AmqpRoutingKey])); } else if (string.Equals(command, "basic.get", StringComparison.OrdinalIgnoreCase)) { basicGetCount++; // Successful responses will have the "message.size" tag // Empty responses will not if (span.Tags.TryGetValue("message.size", out string messageSize)) { Assert.NotNull(span.ParentId); Assert.True(int.TryParse(messageSize, out _)); // Add the parent span ID to a dictionary so we can later assert 1:1 mappings if (distributedParentSpans.TryGetValue(span.ParentId.Value, out int count)) { distributedParentSpans[span.ParentId.Value] = count + 1; } else { distributedParentSpans[span.ParentId.Value] = 1; } } else { emptyBasicGetCount++; } Assert.Equal(SpanKinds.Consumer, span.Tags[Tags.SpanKind]); Assert.NotNull(span.Tags[Tags.AmqpQueue]); // Enforce that the resource name has the following structure: "basic.get [<generated>|{actual queueName}]" string regexPattern = @"basic\.get (?<queueName>\S*)"; var match = Regex.Match(span.Resource, regexPattern); Assert.True(match.Success); var queueName = match.Groups["queueName"].Value; Assert.True(string.Equals(queueName, "<generated>") || string.Equals(queueName, span.Tags[Tags.AmqpQueue])); } else if (string.Equals(command, "basic.deliver", StringComparison.OrdinalIgnoreCase)) { basicDeliverCount++; Assert.NotNull(span.ParentId); // Add the parent span ID to a dictionary so we can later assert 1:1 mappings if (distributedParentSpans.TryGetValue(span.ParentId.Value, out int count)) { distributedParentSpans[span.ParentId.Value] = count + 1; } else { distributedParentSpans[span.ParentId.Value] = 1; } Assert.Equal(SpanKinds.Consumer, span.Tags[Tags.SpanKind]); // Assert.NotNull(span.Tags[Tags.AmqpQueue]); // Java does this but we're having difficulty doing this. Push to v2? Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); Assert.NotNull(span.Tags["message.size"]); Assert.True(int.TryParse(span.Tags["message.size"], out _)); // Enforce that the resource name has the following structure: "basic.deliver [<generated>|{actual queueName}]" string regexPattern = @"basic\.deliver (?<queueName>\S*)"; var match = Regex.Match(span.Resource, regexPattern); // Assert.True(match.Success); // Enable once we can get the queue name included var queueName = match.Groups["queueName"].Value; // Assert.True(string.Equals(queueName, "<generated>") || string.Equals(queueName, span.Tags[Tags.AmqpQueue])); // Enable once we can get the queue name included } else { throw new Xunit.Sdk.XunitException($"amqp.command {command} not recognized."); } } else { Assert.Equal(SpanKinds.Client, span.Tags[Tags.SpanKind]); Assert.Equal(command, span.Resource); if (string.Equals(command, "exchange.declare", StringComparison.OrdinalIgnoreCase)) { exchangeDeclareCount++; Assert.NotNull(span.Tags[Tags.AmqpExchange]); } else if (string.Equals(command, "queue.declare", StringComparison.OrdinalIgnoreCase)) { queueDeclareCount++; Assert.NotNull(span.Tags[Tags.AmqpQueue]); } else if (string.Equals(command, "queue.bind", StringComparison.OrdinalIgnoreCase)) { queueBindCount++; Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpQueue]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); } else { throw new Xunit.Sdk.XunitException($"amqp.command {command} not recognized."); } } } foreach (var span in manualSpans) { Assert.Equal("Samples.RabbitMQ", span.Service); Assert.Equal("1.0.0", span.Tags[Tags.Version]); } } // Assert that all empty get results are expected Assert.Equal(2, emptyBasicGetCount); // Assert that each span that started a distributed trace (basic.publish) // has only one child span (basic.deliver or basic.get) Assert.All(distributedParentSpans, kvp => Assert.Equal(1, kvp.Value)); Assert.Equal(5, basicPublishCount); Assert.Equal(4, basicGetCount); Assert.Equal(3, basicDeliverCount); Assert.Equal(1, exchangeDeclareCount); Assert.Equal(1, queueBindCount); Assert.Equal(4, queueDeclareCount); }
public bool parseStringDEC(string s) { if (s is null || s.Length < MechanicalPoint_DEC_FormatR.Length - 1) { return(true); } // Mount replies to "#GD:" with "sDD:MM:SS". // s is in {+,-} and provides a sign. // DD are degrees, unit D spans '0' to '9' in [0,9] but high D spans '0' to 'I' in [0,25]. // MM are minutes, SS are seconds in [00:00,59:59]. // The whole reply is in [-255:59:59,+255:59:59]. // For flexibility, we allow parsing of +###:##:## instead of the spec +##:##:## Match dms = Regex.Match(s, @"([+\-]([\d:;<=>\?@A-I])\d{1,2})[^\d](\d{2})[^\d](\d{2})"); if (!dms.Success) { return(true); } int degrees = 0; if (4 == dms.Groups[1].Value.Length) { // Sign is processed when DMS is consolidated degrees += int.Parse(dms.Groups[1].Value.Substring(1, 3), formatProvider); } else { switch (dms.Groups[1].Value[1]) { case ':': degrees += 100; break; case ';': degrees += 110; break; case '<': degrees += 120; break; case '=': degrees += 130; break; case '>': degrees += 140; break; case '?': degrees += 150; break; case '@': degrees += 160; break; case 'A': degrees += 170; break; case 'B': degrees += 180; break; case 'C': degrees += 190; break; case 'D': degrees += 200; break; case 'E': degrees += 210; break; case 'F': degrees += 220; break; case 'G': degrees += 230; break; case 'H': degrees += 240; break; case 'I': degrees += 250; break; default: degrees += 10 * int.Parse(dms.Groups[1].Value[1].ToString(formatProvider), formatProvider); break; } degrees += int.Parse(dms.Groups[1].Value[2].ToString(formatProvider), formatProvider); } int minutes = int.Parse(dms.Groups[3].Value, formatProvider); int seconds = int.Parse(dms.Groups[4].Value, formatProvider); _DECm = (dms.Groups[1].Value[0] == '-' ? -1 : +1) * (degrees * 3600 + minutes * 60 + seconds); // Deduce pointing state from mechanical DEC if ((-256 * 3600 < _DECm && _DECm <= -180 * 3600) || (0 <= _DECm && _DECm <= +180 * 3600)) { _pointingState = PointingStates.POINTING_NORMAL; } else { _pointingState = PointingStates.POINTING_BEYOND_POLE; } return(false); }
/// <summary> /// Gets regex fragment matching path fragments. /// </summary> /// <remarks> /// Zero or more acceptable characters will match the /// pattern. This pattern will permit directory separators. /// </remarks> private string GetWildCardRegexPatternForPath() { return string.Concat("[^", Regex.Escape(InvalidPathCharacters), "]*"); }
public System.IO.Stream FillImage(System.IO.Stream imageStream, string fillColor, int?targetImageWidth, int?targetImageHeight) { #region valiation if (imageStream == null) { throw new ArgumentNullException(nameof(imageStream)); } if (string.IsNullOrEmpty(fillColor)) { throw new ArgumentNullException(nameof(fillColor)); } Regex regex = HexColorUtil.GetHexColorRegex(); if (!regex.IsMatch(fillColor)) { throw new ArgumentException($"Color code {fillColor} is malformed!"); } #endregion if (!targetImageWidth.HasValue || !targetImageHeight.HasValue) { return(FillSquareImage(imageStream, fillColor)); } // targetWidth or targetHeight has to be original size, because of positioning image into borders // get original size of image Rect imageDimension = ImageUtil.GetDimensionFromImage(imageStream); int targetWidth = imageDimension.Width; int targetHeight = imageDimension.Height; double scalingFactorWidth = (double)targetImageWidth / (double)imageDimension.Width; double scalingFactorHeight = (double)targetImageHeight / (double)imageDimension.Height; if (scalingFactorHeight == scalingFactorWidth) { // quadratic } else if (scalingFactorWidth > scalingFactorHeight) { targetWidth = (int)((double)targetImageWidth / (double)targetImageHeight * imageDimension.Height); } else { targetHeight = (int)((double)targetImageHeight / (double)targetImageWidth * imageDimension.Width); } // create parameter for resizing image ResizeOptions resizeOptions = new ResizeOptions() { Size = new SixLabors.Primitives.Size(targetWidth, targetHeight), Mode = ResizeMode.BoxPad }; Rgba32 backgroundColor = Rgba32Util.InitFromHex(fillColor); using (Image <Rgba32> originalImage = LoadImageFromStream(imageStream)) using (Image <Rgba32> targetImage = originalImage.Clone(ctx => ctx.Resize(resizeOptions))) { targetImage.Mutate(x => x.BackgroundColor(backgroundColor)); return(SaveAsStream(targetImage)); } }
private string EscapeAndReplaceAsterisk(string s) { s = Regex.Escape(s); return s.Replace("\\*", GetAcceptableCharacterRange()); }
/// <summary> /// 是否是电话号码 格式 区号-电话号码 或者是 7-8位电话号码 或者是 区号 空格 7-8位电话号码 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsTelPhone(this string input) { Regex reg = new Regex(@"^(([\d]{3,4})?([-\s]?)[\d]{7,8})$"); return reg.IsMatch(input); }
/// <summary> /// Replaces the generic parameters with specified values. /// </summary> /// <param name="currentTestStep">The current test step.</param> /// <param name="genericParameters">The generic parameters.</param> private static void ReplaceGenericParametersWithSpecifiedValues(TestStep currentTestStep, Dictionary<string, Dictionary<string, string>> genericParameters) { Regex r1 = new Regex(RegextPatternStepTitle, RegexOptions.Singleline); if (genericParameters.Keys.Count > 0) { Match currentMatch = r1.Match(currentTestStep.Title); string genParamsStr = currentMatch.Groups["GenParam"].Value; string[] genParams = genParamsStr.Split(','); int initializeCount = genParams.Length; bool reinitialized = false; foreach (string currentNamespace in genericParameters.Keys) { if (currentMatch.Success) { if (currentMatch.Groups["Namespace"].Value.EndsWith(currentNamespace)) { currentTestStep.ActionTitle = currentTestStep.OriginalActionTitle; currentTestStep.ActionExpectedResult = currentTestStep.OriginalActionExpectedResult; currentTestStep.Title = currentTestStep.OriginalTitle; reinitialized = true; foreach (string currentKey in genericParameters[currentNamespace].Keys) { initializeCount--; string strToBeReplaced = String.Concat("(", currentKey, ")"); currentTestStep.ActionTitle = currentTestStep.ActionTitle.Replace(strToBeReplaced, genericParameters[currentNamespace][currentKey]); currentTestStep.ActionExpectedResult = currentTestStep.ActionExpectedResult.Replace(strToBeReplaced, genericParameters[currentNamespace][currentKey]); } foreach (string currentGenParam in genParams) { if (!genericParameters[currentNamespace].Keys.Contains(currentGenParam) && genericParameters.Keys.Contains(DefaultGuidString) && genericParameters[DefaultGuidString].Keys.Contains(currentGenParam)) { if (!reinitialized) { currentTestStep.ActionTitle = currentTestStep.OriginalActionTitle; currentTestStep.ActionExpectedResult = currentTestStep.OriginalActionExpectedResult; currentTestStep.Title = currentTestStep.OriginalTitle; } initializeCount--; string strToBeReplaced = String.Concat("(", currentGenParam, ")"); currentTestStep.ActionTitle = currentTestStep.ActionTitle.Replace(strToBeReplaced, genericParameters[DefaultGuidString][currentGenParam]); currentTestStep.ActionExpectedResult = currentTestStep.ActionExpectedResult.Replace(strToBeReplaced, genericParameters[DefaultGuidString][currentGenParam]); } } } } } if (initializeCount != 0) { foreach (string currentGenParam in genParams) { if (genericParameters.Keys.Contains(DefaultGuidString) && genericParameters[DefaultGuidString].Keys.Contains(currentGenParam) && initializeCount != 0) { if (!reinitialized) { currentTestStep.ActionTitle = currentTestStep.OriginalActionTitle; currentTestStep.ActionExpectedResult = currentTestStep.OriginalActionExpectedResult; currentTestStep.Title = currentTestStep.OriginalTitle; reinitialized = true; } initializeCount--; string strToBeReplaced = String.Concat("(", currentGenParam, ")"); currentTestStep.ActionTitle = currentTestStep.ActionTitle.Replace(strToBeReplaced, genericParameters[DefaultGuidString][currentGenParam]); currentTestStep.ActionExpectedResult = currentTestStep.ActionExpectedResult.Replace(strToBeReplaced, genericParameters[DefaultGuidString][currentGenParam]); } } } } else { currentTestStep.ActionTitle = currentTestStep.OriginalActionTitle; currentTestStep.ActionExpectedResult = currentTestStep.OriginalActionExpectedResult; } }
private static bool Matches(Uri url, string regex) { return(Regex.IsMatch(url.ToString(), regex)); }
/// <summary> /// Method to add Answers to the answer list box. This button will also work /// in combination with the edit button to resubmit and edited answer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnAddAnswer_Click(object sender, EventArgs e) { ansEditIndex = Convert.ToInt32(Session["ansEditIndex"]); // regular expression to enure only numbers are entered in the rank text field. Regex reg = new Regex(@"^[-10123456789]+$"); if (tbAnswer.Text.Equals(string.Empty) || tbScore.Text.Equals(string.Empty) || (!reg.IsMatch(tbScore.Text))) { lblErrorAdd.Visible = true; } else { lblErrorAdd.Visible = false; // if (tbQuestion.Enabled == false) { lbAnswerList.Items[ansEditIndex].Text = tbAnswer.Text + " [" + tbScore.Text + "]"; tbQualDesc.Enabled = true; tbQuestion.Enabled = true; lbAnswerList.Enabled = true; btnRemove.Enabled = true; btnClear.Enabled = true; btnEdit.Enabled = true; btnContinue.Enabled = true; btnFinished.Enabled = true; ansEditIndex = 0; } else { //the -1 should be the answer id if it has one ListItem item = new ListItem(tbAnswer.Text + " [" + tbScore.Text + "]", ((lbAnswerList.Items.Count+1)*-1).ToString()); lbAnswerList.Items.Add(item); } tbAnswer.Text = string.Empty; tbScore.Text = string.Empty; } }