private List <Product> ImportProducts(string localFileName) { var result = new List <Product>(); try { var lines = System.IO.File.ReadAllLines(localFileName); System.Text.RegularExpressions.Regex csvParser = new System.Text.RegularExpressions.Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); string[] headerColumns = csvParser.Split(lines.FirstOrDefault()); Dictionary <string, int> columnIndices = GetColumnIndices(headerColumns); var imageIndices = columnIndices.Where(x => x.Key.Contains("Image")).Select(x => x.Value); foreach (var line in lines.Skip(1)) { String[] values = csvParser.Split(line); // clean up the fields (remove " and leading spaces) for (int i = 0; i < values.Length; i++) { values[i] = values[i].TrimStart(' ', '"'); values[i] = values[i].TrimEnd('"'); } var product = new Product(); product.Stock_No = Convert.ToInt32(values[columnIndices["STOCK No"]]); product.chassis_no_1 = values[columnIndices["CHASSIS No 1"]]; product.chassis_no_2 = values[columnIndices["CHASSIS No 2"]]; product.Maker = values[columnIndices["MARCA"]]; product.ProductType = values[columnIndices["TYPE"]]; product.Model = values[columnIndices["NAME OF CAR"]]; product.Grade = values[columnIndices["GRADE"]]; product.Year = values[columnIndices["YEAR"]] == ""? (int?)null : Convert.ToInt32(values[columnIndices["YEAR"]]); product.Month = values[columnIndices["MONTH"]]; product.ETD = values[columnIndices["ETD"]]; product.Color = values[columnIndices["COLOR"]]; product.KM_ran = values[columnIndices["KM"]] == "" ? (int?)null : Convert.ToInt32(values[columnIndices["KM"]].Replace(",", "")); product.Fuel = values[columnIndices["FUEL"]]; product.Gear_m_at = values[columnIndices["GEAR(A/T)"]]; product.CC = values[columnIndices["CC"]] == "" ? (int?)null : Convert.ToInt32(values[columnIndices["CC"]]); product.Price = Convert.ToDecimal(values[columnIndices["SELLING PRICE"]].Replace(",", "")); product.Images = (from imageIndex in imageIndices where values[imageIndex] != "" select values[imageIndex]).ToArray(); product.Equipments = new Equipment(); product.Equipments.AC = values[columnIndices["EQUIPMENT3(A/C)"]] != "" ? true : false; product.Equipments.PS = values[columnIndices["EQUIPMENT2(P/S)"]] != "" ? true : false; product.Equipments.PW = values[columnIndices["EQUIPMENT1(P/W)"]] != "" ? true : false; product.Equipments.WCAB = values[columnIndices["W CAB"]] != "" ? true : false; product.Equipments.FourWheelDrive = values[columnIndices["4 WD"]] != "" ? true : false; var doors = columnIndices.Where(x => x.Key.Contains("DOOR")).Where(y => values[y.Value] != "").Select(x => x.Key.Split(' ')[0]).FirstOrDefault(); product.NoOfDoors = doors == "" || doors == null ? (int?)null : Convert.ToInt32(doors); result.Add(product); } } catch (Exception ex) { throw ex; } finally { System.IO.File.Delete(localFileName); } return(result); }
/** * * */ private void getListImagePath() { String filePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"File\Config.csv"); //String filePath = "pack://application:,,,/Mapeditor;component/File/Config.csv"; listImagePath = new Dictionary <string, string>(); System.IO.StreamReader readerFile = new System.IO.StreamReader(filePath); String data; String[] result; String imgID; String imgPath; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); readerFile.ReadLine(); while ((data = readerFile.ReadLine()) != null) { result = rgx.Split(data); if (result.Length >= 2) { imgID = result[0]; imgPath = result[1]; listImagePath.Add(imgID, imgPath); } } }
private void ParseLine(Products currentProduct, string line, DateTime asOf) { if (line.Length > 0) { var expression = new System.Text.RegularExpressions.Regex(@"\s\s+"); var parts = expression.Split(line.TrimEnd()); if (parts[0].Length > 0 && parts.Length > 1) { var b = new Models.Buyer(); b.Name = parts[0]; switch (currentProduct) { case Products.WinterWheat: ParseColumn(b, parts[1], WINTER_WHEAT, "Ordinary", asOf); ParseColumn(b, parts[2], WINTER_WHEAT, "11 pct", asOf); ParseColumn(b, parts[3], WINTER_WHEAT, "12 pct", asOf); ParseColumn(b, parts[4], WINTER_WHEAT, "13 pct", asOf); break; case Products.SpringWheat: ParseColumn(b, parts[1], SPRING_WHEAT, "13 pct", asOf); ParseColumn(b, parts[2], SPRING_WHEAT, "14 pct", asOf); ParseColumn(b, parts[3], SPRING_WHEAT, "15 pct", asOf); break; case Products.DurumWheat: ParseColumn(b, parts[1], DURUM_WHEAT, "13 pct", asOf); ParseColumn(b, parts[2], "Barley", "Malt", asOf); ParseColumn(b, parts[3], "Barley", "Feed", asOf); break; } } } }
private string[] ParseDelimited(string str1, string del, string qual) { string[] tmp; if (qual != "") { string pattern = del + "(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pattern); tmp = r.Split(str1); string trimstring = " \n\r" + qual; if (qual != "") { for (int x = 0; x < tmp.Length; x++) { tmp[x] = tmp[x].Trim(trimstring.ToCharArray()); tmp[x] = tmp[x].Replace(qual + qual, qual); } } } else { tmp = str1.Split(del.ToCharArray()); } return(tmp); }
public static string SetUrl(string Url) { if (Url == null) { return(""); } string seourl = ""; seourl = Url.Trim(); seourl = seourl.ToLower(); seourl = seourl.Replace("ğ", "g"); seourl = seourl.Replace("Ğ", "G"); seourl = seourl.Replace("ü", "u"); seourl = seourl.Replace("Ü", "U"); seourl = seourl.Replace("ş", "s"); seourl = seourl.Replace("Ş", "S"); seourl = seourl.Replace("ı", "i"); seourl = seourl.Replace("İ", "I"); seourl = seourl.Replace("ö", "o"); seourl = seourl.Replace("Ö", "O"); seourl = seourl.Replace("ç", "c"); seourl = seourl.Replace("Ç", "C"); seourl = seourl.Replace("-", "+"); seourl = seourl.Replace(" ", "+"); seourl = seourl.Trim(); seourl = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(seourl, ""); seourl = seourl.Trim(); seourl = seourl.Replace("+", "-"); string seourlson = ""; string[] a = seourl.Split('-'); seourlson = string.Join("-", a.Where(x => !string.IsNullOrEmpty(x))); return(seourlson); }
/* * public void Add(string text, params object[] args) * { * Add(Images.None, String.Format(text, args)); * } * * public void Add(Images img, string text, params object[] args) * { * Add(Images.None, String.Format(text, args)); * } */ private void DecodeString(string text, ref ListElement L) { System.Text.RegularExpressions.Regex x = new System.Text.RegularExpressions.Regex("\n"); string[] w = x.Split(text); foreach (string input in w) { Graphics g = listBox1.CreateGraphics(); int maxTextWidth = this.Width - (50 + 100); if (g.MeasureString(input, listBox1.Font).Width > maxTextWidth) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("([ \typet{}():;])"); string[] words = r.Split(input); StringBuilder b = new StringBuilder(); foreach (string s in words) { if (g.MeasureString(b.ToString() + s, listBox1.Font).Width > maxTextWidth) { L.text.Add(b.ToString()); b = new StringBuilder(); } b.Append(s); } if (b.Length > 0) { L.text.Add(b.ToString()); } } else { L.text.Add(input); } } }
/// <summary>Speak the text.</summary> public void Speak() { Silence(); stack.Clear(); clipDict.Clear(); foreach (AudioClip clip in Clips) { clipDict.Add("#" + clip.name + "#", clip); } string[] speechParts = splitRegex.Split(Text).Where(s => s != string.Empty).ToArray(); System.Text.RegularExpressions.MatchCollection mc = splitRegex.Matches(Text); int index = 0; foreach (System.Text.RegularExpressions.Match match in mc) { //Debug.Log("MATCH: '" + match + "' - " + Text.IndexOf(match.ToString(), index)); stack.Add(index = Text.IndexOf(match.ToString(), index), match.ToString()); index++; } index = 0; foreach (string speech in speechParts) { //Debug.Log("PART: '" + speech + "' - " + Text.IndexOf(speech, index)); stack.Add(index = Text.IndexOf(speech, index), speech); index++; } StartCoroutine(processStack()); }
/// <summary> /// Parsing input string to SLAE /// </summary> /// <param name="slaeString">String which contains elements of slae</param> private static Slae ParseSlaeString(string slaeString) { System.Text.RegularExpressions.Regex rowSplitter = new System.Text.RegularExpressions.Regex(@"\r?\n");// \\d+\\.?\\d?\\s var rows = rowSplitter.Split(slaeString).Where(r => r.Length != 0).ToList(); double[][] Matrix = new double[rows.Count][]; double[] B = new double[rows.Count]; for (int i = 0; i < rows.Count; i++) { string[] elements = rows[i].Split(' '); if (rows.Count + 1 == elements.Length) { List <double> readValues = new List <double>(); for (int j = 0; j < elements.Length - 1; j++) { readValues.Add(Double.Parse(elements[j])); } var b = Double.Parse(elements[elements.Length - 1]); Matrix[i] = readValues.ToArray(); B[i] = b; } else { throw new ArgumentException(); } } return(new Slae(Matrix, B)); }
public static (int coordX, int coordY) GetTheCoords(string message, Ocean playerEmptyBoard) { int coordX = 0; int coordY = 0; bool validInput = false; string pattern = @"([a-zA-Z])([0-9].*)"; var regex = new System.Text.RegularExpressions.Regex(pattern); var coordsRange = Enumerable.Range(0, 10); while (!validInput) { string userInput = PrintMessageToGetInput(message + "\nGive XY as letter + number:"); if (!new[] { 2, 3 }.Contains(userInput.Length)) { continue; } string userInputX; string userInputY; try { userInputX = regex.Split(userInput)[1]; userInputY = regex.Split(userInput)[2]; } catch (IndexOutOfRangeException) { continue; } coordX = UTILS.Utils.LetterToNumber(userInputX); validInput = int.TryParse(userInputY, out coordY); coordY--; if (playerEmptyBoard.ArrayOfSquares[coordX, coordY].AlreadyShooted) { validInput = false; Console.WriteLine("Already shooted..."); continue; } else if (coordX == 10 || !coordsRange.Contains(coordY)) { validInput = false; continue; } } return(coordX, coordY); }
public void SetText(string text) { Textarea.Text = text; var liner = new System.Text.RegularExpressions.Regex("\n"); lines = liner.Split(text).Length; Textarea.Height = 20 * Math.Min(lines+1,7) + 4; Height = Textarea.Height + 28; }
private bool configureDB(string[] installArgs) { // create the AM Database System.Data.SqlClient.SqlConnection conAMDB = new System.Data.SqlClient.SqlConnection(buildConnectString(installArgs, false, false)); System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); try { // Open connection to the server as the user provided in setup. conAMDB.Open(); // Set up the tables. System.Text.RegularExpressions.Regex goRegExp = new System.Text.RegularExpressions.Regex("GO", System.Text.RegularExpressions.RegexOptions.Singleline); string queries = GetSql("sql.txt"); string [] individualQueries = goRegExp.Split(queries); foreach (string query in individualQueries) { cmd.CommandText = query; cmd.Connection = conAMDB; cmd.ExecuteNonQuery(); } // Set up the data. queries = GetSql("data.txt"); individualQueries = goRegExp.Split(queries); foreach (string query in individualQueries) { cmd.CommandText = query; cmd.Connection = conAMDB; cmd.ExecuteNonQuery(); } } catch (System.Exception) { return(false); } finally { conAMDB.Close(); } return(true); }
public IActionResult TuberculosisHome(string filter) { var rx = new System.Text.RegularExpressions.Regex(" - "); var array = rx.Split(filter); var firstDay = array[0]; var lastDay = array[1]; GraphFunc("TuberculosisGraph", Convert.ToDateTime(firstDay), Convert.ToDateTime(lastDay)); return(View()); }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex(":"); string[] words = regex.Split(str); Assert.Equal(new[] { FILL_ME_IN }, words); //A full treatment of regular expressions is beyond the scope //of this tutorial. The book "Mastering Regular Expressions" //is highly recommended to be on your bookshelf }
public IActionResult ChildCare(string filter) { var province = HttpContext.Session.GetString("province_id"); var rx = new System.Text.RegularExpressions.Regex(" - "); var array = rx.Split(filter); var firstDay = array[0]; var lastDay = array[1]; var child_graph = _context.ChildCareGraph.FromSqlRaw($"EXEC EFHSIS.dbo.ChildCareGraph @date_start = N'{firstDay}',@date_end = N'{lastDay}',@prov_code = N'{province}';"); ViewBag.DataPoints = JsonConvert.SerializeObject(child_graph); return(View()); }
public static string WrapText(DynamicSpriteFont font, TextSnippet[] snippets, string fullText, float maxLineWidth, float fontScale = 1f) { var regex = new System.Text.RegularExpressions.Regex(@"\s+(?![^\[]*\])"); string baseText = ""; foreach (TextSnippet snippet in snippets) { baseText += snippet.Text; } if (string.IsNullOrEmpty(baseText)) { return(""); } string[] lines = baseText.Split('\n'); string[] actualLines = fullText.Split('\n'); string newText = ""; float currentWidth = 0f; float spaceWidth = font.MeasureString(" ").X *fontScale; for (int i = 0; i < Math.Min(lines.Length, actualLines.Length); i++) { string line = lines[i]; string[] words = line.Split(' '); string[] actualWords = regex.Split(actualLines[i]); for (int k = 0; k < Math.Min(words.Length, actualWords.Length); k++) { string word = words[k]; string actualWord = actualWords[k]; Vector2 wordSize = font.MeasureString(word) * fontScale; if (currentWidth + wordSize.X < maxLineWidth) { newText += actualWord + " "; currentWidth += wordSize.X + spaceWidth; continue; } newText += Environment.NewLine + actualWord + " "; currentWidth = wordSize.X + spaceWidth; } currentWidth = 0f; if (i < lines.Length - 1) { newText += "\n"; } } return(newText); }
/// <summary> /// Returns a splitted string into Array of String. /// </summary> /// <param name="strSource">Input String having all codes separated with ','</param> /// <param name="strReturn">Array of splitted string.</param> /// <param name="strSeparator"></param> public void SplitString(String strSource, ref String[] strReturn, String strSeparator) { if (!object.ReferenceEquals(strSource, String.Empty) || strSource.Length != 0) { RemoveLastSeparator(ref strSource, strSeparator); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(strSeparator); strReturn = regex.Split(strSource); } else { strSource = null; } }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex(":"); string[] words = regex.Split(str); CollectionAssert.AreEqual(new[] { "the", "rain", "in", "spain" }, words, "La manera en què Eliza Doolittle va parlar per primer cop a 'My Fair Lady' trencaria el karma de qualsevol."); //El tractament de les expressions regulars queda fora de l'àmbit d'aquesta pràctica/tutorial. //El llibre "Mastering Regular Expressions" per això, és una bona referència per tenir a la //vostra biblioteca de llibres de programació: //http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex(":"); string[] words = regex.Split(str); CollectionAssert.AreEqual(new[] { "the", "rain", "in", "spain" }, words, "The way Eliza Doolittle first spoke in 'My Fair Lady' would break anyone's Karma."); //A full treatment of regular expressions is beyond the scope //of this tutorial. The book "Mastering Regular Expressions" //is highly recommended to be on your bookshelf: //http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 }
private void SetRichTextBox(string contentFile) { rtbRuleEditFile.Clear(); var regex = new System.Text.RegularExpressions.Regex(Environment.NewLine); String[] lines = regex.Split(contentFile); foreach (string l in lines) { ParseLine(l); } }
public static (int coordX, int coordY) GetTheCoords(string message) { int coordX = 0; int coordY = 0; bool validInput = false; string pattern = @"([a-zA-Z])([0-9].*)"; var regex = new System.Text.RegularExpressions.Regex(pattern); var coordsRange = Enumerable.Range(0, 10); while (!validInput) { string userInput = GetTheInput(message + "\nGive XY as letter + number:"); if (!(new[] { 2, 3 }.Contains(userInput.Length))) { continue; } string userInputX; string userInputY; try { userInputX = regex.Split(userInput)[1]; userInputY = regex.Split(userInput)[2]; } catch (IndexOutOfRangeException) { continue; } coordX = UTILS.Utils.LetterToNumber(userInputX); validInput = int.TryParse(userInputY, out coordY); coordY--; if (coordX == 10 || !coordsRange.Contains(coordY)) { validInput = false; continue; } } return(coordX, coordY); }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex(":"); string[] words = regex.Split(str); Assert.Equal(new[] { "the", "rain", "in", "spain" }, words); //I for real don't know what this is teaching me. Why not use str.Split(':')? //A full treatment of regular expressions is beyond the scope //of this tutorial. The book "Mastering Regular Expressions" //is highly recommended to be on your bookshelf }
public static string[] GetArgs(string cmd) { if (string.IsNullOrEmpty (cmd)) { return new string[] { }; } var strExp = "\".*?\""; var cmdStr = new System.Text.RegularExpressions.Regex(strExp).Replace(cmd, m => { var r = m.Value.Replace(" ", _space); return r; }); return cmdStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); }
private static void ThreadExceptionHandler(Task t) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(" "); string[] StackTrace = r.Split(t.Exception.InnerException.StackTrace); System.Text.StringBuilder newStackTrace = new System.Text.StringBuilder(); newStackTrace.Append("Fatal error: " + t.Exception.InnerException.GetType().ToString() + ": " + t.Exception.InnerException.Message + "\r\n"); for (int i = 0; i < StackTrace.Length - 1; i++) { newStackTrace.Append(" " + StackTrace[i]); } Console.WriteLine(newStackTrace.ToString()); Stop(); Console.WriteLine("Game stopped"); }
internal static Dictionary <string, string> SplitNotes(string notes) { Dictionary <string, string> dict = new Dictionary <string, string>(); if (notes != null) { System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@"\$([A-Z]{2})\$"); string[] parts = regex2.Split(notes, 10); for (int i = 1; i < parts.Length; i += 2) { dict[parts[i]] = (parts.Length > i + 1) ? parts[i + 1] : ""; } } return(dict); }
public static string[] GetArgs(string cmd) { if (string.IsNullOrEmpty(cmd)) { return(new string[] { }); } var strExp = "\".*?\""; var cmdStr = new System.Text.RegularExpressions.Regex(strExp).Replace(cmd, m => { var r = m.Value.Replace(" ", _space); return(r); }); return(cmdStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)); }
public bool TryParse(string str, out double value, out string message) { message = string.Empty; value = double.NaN; var ss = _doubleRege.Split(str).Where(t => { var s = t.Trim(); return(!(s == "," || s == "" || s == ",")); }); string num = ""; string unit = ""; foreach (var s in ss) { if (_doubleRege.IsMatch(s)) { num = s; continue; } if (_unitRegex.IsMatch(s)) { unit = s; continue; } } string vl = string.IsNullOrEmpty(unit) ? string.Empty : str.Replace(unit, string.Empty); // Do :验证单位部分是否合法 if (!this.TryUnit(unit, out message)) { return(false); } // Do :验证值部分是否合法 if (double.TryParse(vl, out value)) { return(true); } message = $"{vl}值不合法,请尝试输入<{num}{unit}>格式"; return(false); }
private string _makeItemAlpha(string itemExpression) { var reg = new System.Text.RegularExpressions.Regex("[ ]"); var alpha = reg.Split(itemExpression).Select(x => { var first = _appModel.Morphs.FirstOrDefault(p => p.Morph == x); if (first == null) { return("?"); } return(first.Alpha); }) .Aggregate((a, b) => a + "_" + b); return(alpha); }
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { if (value != null && string.IsNullOrEmpty(value as string) == false) { ObservableCollection <MorphModel> morphCollection = MorphCollection.Source as ObservableCollection <MorphModel>; var itemExp = value as string; var regws = new System.Text.RegularExpressions.Regex(" +"); foreach (var morph in regws.Split(itemExp)) { if (morphCollection.Any(x => x.Morph == morph) == false) { return(new ValidationResult(false, value)); } } } return(new ValidationResult(true, null)); }
public void FindNer(string context) { if (locationNameFinder == null) { Initial(); } var tokens = regex.Split(context); // Find location names var locations = new List <string>(); opennlp.tools.util.Span[] locationSpan = locationNameFinder.find(tokens); //important: clear adaptive data in the feature generators or the detection rate will decrease over time. locationNameFinder.clearAdaptiveData(); locations.AddRange(opennlp.tools.util.Span.spansToStrings(locationSpan, tokens).AsEnumerable()); // Find person names var persons = new List <string>(); opennlp.tools.util.Span[] personSpan = personNameFinder.find(tokens); //important: clear adaptive data in the feature generators or the detection rate will decrease over time. personNameFinder.clearAdaptiveData(); persons.AddRange(opennlp.tools.util.Span.spansToStrings(personSpan, tokens).AsEnumerable()); // Find organization names var organizations = new List <string>(); opennlp.tools.util.Span[] organizationSpan = organizationNameFinder.find(tokens); //important: clear adaptive data in the feature generators or the detection rate will decrease over time. organizationNameFinder.clearAdaptiveData(); organizations.AddRange(opennlp.tools.util.Span.spansToStrings(organizationSpan, tokens).AsEnumerable()); entities = new List <pml.type.Pair <string, string> >(); foreach (var location in locations) { entities.Add(new pml.type.Pair <string, string>(location, "LOCATION")); } foreach (var person in persons) { entities.Add(new pml.type.Pair <string, string>(person, "PERSON")); } foreach (var organization in organizations) { entities.Add(new pml.type.Pair <string, string>(organization, "ORGANIZATION")); } }
/// <summary> /// Gets the String-value of Short Date from Date data. /// </summary> /// <returns>string-value of Short date format.</returns> static public String TruncateDate(String strSource, String strCultureInfo) { DateTimeFormatInfo objDTFI = new CultureInfo(strCultureInfo, false).DateTimeFormat; DateTime dtmTemp = DateTime.Now; String strResult = String.Empty; if (!strSource.Equals(String.Empty)) { if (DateTime.TryParse(strSource, objDTFI, DateTimeStyles.None, out dtmTemp)) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(" "); String[] strDate = regEx.Split(dtmTemp.ToShortDateString()); strResult = strDate[0]; } } return(strResult); }
private void DataTypeView_CopyAllCols_Click(object sender, RoutedEventArgs e) { // determine width to align tab character to int typeWidth = "DataType".Length, valWidth = "Cannot parse.".Length, offsetWidth = "Offset (hex)".Length; foreach (StructListItem item in DataTypeListView.SelectedItems) { typeWidth = item.DataTypeCol?.Length > typeWidth ? item.DataTypeCol.Length : typeWidth; valWidth = item.ValueCol?.Length > valWidth ? item.ValueCol.Length : valWidth; offsetWidth = item.OffsetCol?.Length > offsetWidth ? item.OffsetCol.Length : offsetWidth; } // format string String fstr = $"{{0,-{typeWidth}}}\t|\t{{1,-{valWidth}}}\t|\t{{2,-{offsetWidth}}}{{3}}"; // start the string with header String str = String.Format(fstr, "DataType", "Value", "Offset (hex)", Environment.NewLine); // add each entry foreach (StructListItem item in DataTypeListView.SelectedItems) { var valStr = item.ValueCol; // align binary // 11111111 00000000 // 00000000 11111111 if (item.DataTypeCol == "binary") { str += String.Format(fstr, item.DataTypeCol, "", item.OffsetCol + "h", Environment.NewLine); var re = new System.Text.RegularExpressions.Regex(Environment.NewLine); var rows = re.Split(valStr); foreach (var row in rows) { str += String.Format(fstr, "", row, "", Environment.NewLine); } } else { str += String.Format(fstr, item.DataTypeCol, valStr, item.OffsetCol + "h", Environment.NewLine); } } Clipboard.SetDataObject(str); Clipboard.Flush(); }
static public Variable Tokenize(string data, string sep, string option = "") { if (sep == "\\t") { sep = "\t"; } string[] tokens; var sepArray = sep.ToCharArray(); if (sepArray.Count() == 1) { tokens = data.Split(sepArray); } else { List <string> tokens_ = new List <string>(); var rx = new System.Text.RegularExpressions.Regex(sep); tokens = rx.Split(data); for (int i = 0; i < tokens.Length; i++) { if (string.IsNullOrWhiteSpace(tokens[i]) || sep.Contains(tokens[i])) { continue; } tokens_.Add(tokens[i]); } tokens = tokens_.ToArray(); } List <Variable> results = new List <Variable>(); for (int i = 0; i < tokens.Length; i++) { string token = tokens[i]; if (i > 0 && string.IsNullOrWhiteSpace(token) && option.StartsWith("prev", StringComparison.OrdinalIgnoreCase)) { token = tokens[i - 1]; } results.Add(new Variable(token)); } return(new Variable(results)); }
//************************************************************* public static bool fetch_messages(string project_user, string project_password, int projectid) { // experimental, under construction POP3Client.POP3client client = new POP3Client.POP3client(Pop3ReadInputStreamCharByChar); string[] SubjectCannotContainStrings = btnet.Util.rePipes.Split(Pop3SubjectCannotContain); string[] FromCannotContainStrings = btnet.Util.rePipes.Split(Pop3FromCannotContain); //try { System.Data.DataRow defaults = Bug.get_bug_defaults(); //int projectid = (int)defaults["pj"]; int categoryid = (int)defaults["ct"]; int priorityid = (int)defaults["pr"]; int statusid = (int)defaults["st"]; int udfid = (int)defaults["udf"]; btnet.Util.write_to_log("pop3:" + client.connect(Pop3Server, Pop3Port, Pop3UseSSL)); btnet.Util.write_to_log("pop3:sending POP3 command USER"); btnet.Util.write_to_log("pop3:" + client.USER(project_user)); btnet.Util.write_to_log("pop3:sending POP3 command PASS"); btnet.Util.write_to_log("pop3:" + client.PASS(project_password)); btnet.Util.write_to_log("pop3:sending POP3 command STAT"); btnet.Util.write_to_log("pop3:" + client.STAT()); btnet.Util.write_to_log("pop3:sending POP3 command LIST"); string list; list = client.LIST(); btnet.Util.write_to_log("pop3:list follows:"); btnet.Util.write_to_log(list); string[] messages = null; System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\r\n"); messages = regex.Split(list); int end = messages.Length - 1; // loop through the messages for (int i = 1; i < end; i++) { int space_pos = messages[i].IndexOf(" "); int message_number = Convert.ToInt32(messages[i].Substring(0, space_pos)); string message_raw_string = client.RETR(message_number); if (Pop3WriteRawMessagesToLog) { btnet.Util.write_to_log("raw email message:"); btnet.Util.write_to_log(message_raw_string); } SharpMimeMessage mime_message = MyMime.get_sharp_mime_message(message_raw_string); string from_addr = MyMime.get_from_addr(mime_message); string subject = MyMime.get_subject(mime_message); if (Pop3SubjectMustContain != "" && subject.IndexOf(Pop3SubjectMustContain) < 0) { btnet.Util.write_to_log("skipping because subject does not contain: " + Pop3SubjectMustContain); continue; } bool bSkip = false; for (int k = 0; k < SubjectCannotContainStrings.Length; k++) { if (SubjectCannotContainStrings[k] != "") { if (subject.IndexOf(SubjectCannotContainStrings[k]) >= 0) { btnet.Util.write_to_log("skipping because subject cannot contain: " + SubjectCannotContainStrings[k]); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } if (Pop3FromMustContain != "" && from_addr.IndexOf(Pop3FromMustContain) < 0) { btnet.Util.write_to_log("skipping because from does not contain: " + Pop3FromMustContain); continue; // that is, skip to next message } for (int k = 0; k < FromCannotContainStrings.Length; k++) { if (FromCannotContainStrings[k] != "") { if (from_addr.IndexOf(FromCannotContainStrings[k]) >= 0) { btnet.Util.write_to_log("skipping because from cannot contain: " + FromCannotContainStrings[k]); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } int bugid = MyMime.get_bugid_from_subject(ref subject); string cc = MyMime.get_cc(mime_message); string comment = MyMime.get_comment(mime_message); string headers = MyMime.get_headers_for_comment(mime_message); if (headers != "") { comment = headers + "\n" + comment; } Security security = MyMime.get_synthesized_security(mime_message, from_addr, Pop3ServiceUsername); int orgid = security.user.org; if (bugid == 0) { if (security.user.forced_project != 0) { projectid = security.user.forced_project; } if (subject.Length > 200) { subject = subject.Substring(0, 200); } btnet.Bug.NewIds new_ids = btnet.Bug.insert_bug( subject, security, "", // tags projectid, orgid, categoryid, priorityid, statusid, 0, // assignedid, udfid, "", "", "", // project specific dropdown values comment, comment, from_addr, cc, "text/plain", false, // internal only null, // custom columns false); MyMime.add_attachments(mime_message, new_ids.bugid, new_ids.postid, security); // your customizations Bug.apply_post_insert_rules(new_ids.bugid); btnet.Bug.send_notifications(btnet.Bug.INSERT, new_ids.bugid, security); btnet.WhatsNew.add_news(new_ids.bugid, subject, "added", security); MyPop3.auto_reply(new_ids.bugid, from_addr, subject, projectid); } else // update existing { string StatusResultingFromIncomingEmail = Util.get_setting("StatusResultingFromIncomingEmail", "0"); string sql = ""; if (StatusResultingFromIncomingEmail != "0") { sql = @"update bugs set bg_status = $st where bg_id = $bg "; sql = sql.Replace("$st", StatusResultingFromIncomingEmail); } sql += "select bg_short_desc from bugs where bg_id = $bg"; sql = sql.Replace("$bg", Convert.ToString(bugid)); DataRow dr2 = btnet.DbUtil.get_datarow(sql); // Add a comment to existing bug. int postid = btnet.Bug.insert_comment( bugid, security.user.usid, // (int) dr["us_id"], comment, comment, from_addr, cc, "text/plain", false); // internal only MyMime.add_attachments(mime_message, bugid, postid, security); btnet.Bug.send_notifications(btnet.Bug.UPDATE, bugid, security); btnet.WhatsNew.add_news(bugid, (string)dr2["bg_short_desc"], "updated", security); } if (Pop3DeleteMessagesOnServer) { btnet.Util.write_to_log("sending POP3 command DELE"); btnet.Util.write_to_log(client.DELE(message_number)); } } } //catch (Exception ex) //{ // btnet.Util.write_to_log("pop3:exception in fetch_messages: " + ex.Message); // error_count++; // if (error_count > Pop3TotalErrorsAllowed) // { // return false; // } //} btnet.Util.write_to_log("pop3:quit"); btnet.Util.write_to_log("pop3:" + client.QUIT()); return true; }
private List<Product> ImportProducts(string localFileName) { var result = new List<Product>(); try { var lines = System.IO.File.ReadAllLines(localFileName); System.Text.RegularExpressions.Regex csvParser = new System.Text.RegularExpressions.Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); string[] headerColumns = csvParser.Split(lines.FirstOrDefault()); Dictionary<string, int> columnIndices = GetColumnIndices(headerColumns); var imageIndices = columnIndices.Where(x => x.Key.Contains("Image")).Select(x => x.Value); foreach (var line in lines.Skip(1)) { String[] values = csvParser.Split(line); // clean up the fields (remove " and leading spaces) for (int i = 0; i < values.Length; i++) { values[i] = values[i].TrimStart(' ', '"'); values[i] = values[i].TrimEnd('"'); } var product = new Product(); product.Stock_No = Convert.ToInt32(values[columnIndices["STOCK No"]]); product.chassis_no_1 = values[columnIndices["CHASSIS No 1"]]; product.chassis_no_2 = values[columnIndices["CHASSIS No 2"]]; product.Maker = values[columnIndices["MARCA"]]; product.ProductType = values[columnIndices["TYPE"]]; product.Model = values[columnIndices["NAME OF CAR"]]; product.Grade = values[columnIndices["GRADE"]]; product.Year = values[columnIndices["YEAR"]] == ""? (int?)null : Convert.ToInt32(values[columnIndices["YEAR"]]); product.Month = values[columnIndices["MONTH"]]; product.ETD = values[columnIndices["ETD"]]; product.Color = values[columnIndices["COLOR"]]; product.KM_ran = values[columnIndices["KM"]] == "" ? (int?)null : Convert.ToInt32(values[columnIndices["KM"]].Replace(",", "")); product.Fuel = values[columnIndices["FUEL"]]; product.Gear_m_at = values[columnIndices["GEAR(A/T)"]]; product.CC = values[columnIndices["CC"]] == "" ? (int?)null : Convert.ToInt32(values[columnIndices["CC"]]); product.Price = Convert.ToDecimal(values[columnIndices["SELLING PRICE"]].Replace(",","")); product.Images = (from imageIndex in imageIndices where values[imageIndex] != "" select values[imageIndex]).ToArray(); product.Equipments = new Equipment(); product.Equipments.AC = values[columnIndices["EQUIPMENT3(A/C)"]] != "" ? true : false; product.Equipments.PS = values[columnIndices["EQUIPMENT2(P/S)"]] != "" ? true : false; product.Equipments.PW = values[columnIndices["EQUIPMENT1(P/W)"]] != "" ? true : false; product.Equipments.WCAB = values[columnIndices["W CAB"]] != "" ? true : false; product.Equipments.FourWheelDrive = values[columnIndices["4 WD"]] != "" ? true : false; var doors = columnIndices.Where(x => x.Key.Contains("DOOR")).Where(y => values[y.Value] != "").Select(x => x.Key.Split(' ')[0]).FirstOrDefault(); product.NoOfDoors = doors == "" || doors == null ? (int?)null : Convert.ToInt32(doors); result.Add(product); } } catch (Exception ex) { throw ex; } finally { System.IO.File.Delete(localFileName); } return result; }
// Using the Compare function of IComparer public int Compare(object x, object y) { // Cast the objects to ListViewItems ListViewItem lvi1 = (ListViewItem)x; ListViewItem lvi2 = (ListViewItem)y; // If the column is string if (column < 1) { //try to convert to doubles first double first; double second; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("(^[<(]\\d+[;]\\d+[>)]$)"); System.Text.RegularExpressions.Regex r1 = new System.Text.RegularExpressions.Regex("[<>();]"); if ((Double.TryParse(lvi1.SubItems[column].Text, out first)) && (Double.TryParse(lvi2.SubItems[column].Text, out second))) { //it is double then if (bAscending) return first > second ? 1 : (first < second ? -1 : 0); // Return the negated Compare return first > second ? -1 : (first < second ? 1 : 0); } else if ((r.IsMatch(lvi1.SubItems[column].Text)) && (r.IsMatch(lvi2.SubItems[column].Text))) { //hooray, an interval string[] numbers = r1.Split(lvi1.SubItems[column].Text); string[] numbers1 = r1.Split(lvi2.SubItems[column].Text); if ((numbers.Length > 1) && (numbers1.Length > 1) && (Double.TryParse(numbers[1], out first)) && (Double.TryParse(numbers1[1], out second))) { if (bAscending) return first > second ? 1 : (first < second ? -1 : 0); // Return the negated Compare return first > second ? -1 : (first < second ? 1 : 0); } } else { //if nothing works, it is a string string lvi1String = lvi1.SubItems[column].ToString(); string lvi2String = lvi2.SubItems[column].ToString(); // Return the normal Compare if (bAscending) return String.Compare(lvi1String, lvi2String); // Return the negated Compare return -String.Compare(lvi1String, lvi2String); } } // The column is double double lvi1Int = Convert.ToDouble(lvi1.SubItems[column].Text.ToString()); double lvi2Int = Convert.ToDouble(lvi2.SubItems[column].Text.ToString()); // Return the normal compare.. if x < y then return -1 if (bAscending) { if (lvi1Int < lvi2Int) return -1; else if (lvi1Int == lvi2Int) return 0; return 1; } // Return the opposites for descending if (lvi1Int > lvi2Int) return -1; else if (lvi1Int == lvi2Int) return 0; return 1; }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex (":"); string[] words = regex.Split (str); CollectionAssert.AreEqual (new[] { "the","rain","in","spain" }, words, "The way Eliza Doolittle first spoke in 'My Fair Lady' would break anyone's Karma."); //A full treatment of regular expressions is beyond the scope //of this tutorial. The book "Mastering Regular Expressions" //is highly recommended to be on your bookshelf: //http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 }
private void btnLoad_Click(object sender, EventArgs e) { Int64 iCounter = 0; string regexCSVSplit = string.Empty; regexCSVSplit = ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"; regexCSVSplit = @"([^\\x22\\]*(:?:\\.[^\\x22\\]*)*)\\x22,?|([^,]+),?|,"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(regexCSVSplit); string tableName = "MaxMindData"; string cityPartition = "Cities"; string blockPartition = "IPBlocks"; this.Cursor = Cursors.WaitCursor; System.IO.StreamReader file = new System.IO.StreamReader(txtCityFile.Text); string inputString = string.Empty; AzureTableStorage ats = new AzureTableStorage(txtAccount.Text, txtEndpoint.Text, txtSharedKey.Text, "SharedKey"); StringBuilder sb = new StringBuilder(); sb.AppendFormat(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <entry xml:base=""http://finseldemos.table.core.windows.net/"" xmlns:d=""http://schemas.microsoft.com/ado/2007/08/dataservices"" xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"" xmlns=""http://www.w3.org/2005/Atom"">"); int entityCount = 0; ats.Tables(cmdType.post, tableName); inputString = file.ReadLine(); // read copyright inputString = file.ReadLine(); // read column headers azureHelper ah = new azureHelper(ats.auth); while ((inputString = file.ReadLine()) != null) { iCounter++; string[] dataSet = r.Split(inputString); for (int i = 0; i < dataSet.GetUpperBound(0); i++) dataSet[i] = dataSet[i].ToString().Replace("\"", ""); if ((iCounter % 100) == 0) { Notify(string.Format("Processing location {0}: {1}", iCounter, DateTime.Now.ToString("O"))); } //locId,country,region,city,postalCode,latitude,longitude,metroCode,areaCode // string ds = string.Format(locationTemplate, tableName, cityPartition, dataSet[0], inputString); sb.AppendFormat(locationTemplate, dataSet); entityCount++; if (entityCount >= 99) { sb.Append("</entry>"); // Notify(string.Format("Transmitting Group of transactions, processed through {0}",iCounter)); ah.entityGroupTransaction(cmdType.post , tableName, sb.ToString()); sb = new StringBuilder(); sb.AppendFormat(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <entry xml:base=""http://finseldemos.table.core.windows.net/"" xmlns:d=""http://schemas.microsoft.com/ado/2007/08/dataservices"" xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"" xmlns=""http://www.w3.org/2005/Atom"">"); entityCount = 0; } if ((iCounter % 100)==0) Application.DoEvents(); } if (entityCount > 0) { Notify("Transmitting Final Group of transactions"); sb.Append("</entry>"); ah.entityGroupTransaction(cmdType.post, tableName, sb.ToString()); sb = new StringBuilder(); entityCount = 0; } file.Close(); sb = new StringBuilder(); iCounter = 0; sb.AppendFormat(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <entry xml:base=""http://finseldemos.table.core.windows.net/"" xmlns:d=""http://schemas.microsoft.com/ado/2007/08/dataservices"" xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"" xmlns=""http://www.w3.org/2005/Atom"">"); entityCount = 0; file = new System.IO.StreamReader(txtBlocksFile.Text); inputString = string.Empty; inputString = file.ReadLine(); // read copyright inputString = file.ReadLine(); // read column headers Int64 ipLoadRecord = 0; while ((inputString = file.ReadLine()) != null) { iCounter++; string[] dataSet = r.Split(inputString); for (int i = 0; i < dataSet.GetUpperBound(0); i++) dataSet[i] = dataSet[i].ToString().Replace("\"", ""); if ((iCounter % 100) == 0) { Notify(string.Format("Processing location {0}: {1}", iCounter, DateTime.Now.ToString("O"))); } sb.AppendFormat(ipTemplate, dataSet); entityCount++; if (entityCount >= 500) { sb.Append("</entry>"); Notify(string.Format("Transmitting Group of transactions, processed through {0}",iCounter)); ah.entityGroupTransaction(cmdType.post, tableName, sb.ToString()); sb = new StringBuilder(); sb.AppendFormat(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <entry xml:base=""http://finseldemos.table.core.windows.net/"" xmlns:d=""http://schemas.microsoft.com/ado/2007/08/dataservices"" xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"" xmlns=""http://www.w3.org/2005/Atom"">"); entityCount = 0; } if ((iCounter % 100) == 0) { Notify(string.Format("Processed through {0}", iCounter)); Application.DoEvents(); } } if (entityCount > 0) { Notify("Transmitting Final Group of transactions"); sb.Append("</entry>"); ah.entityGroupTransaction(cmdType.post, tableName, sb.ToString()); sb = new StringBuilder(); entityCount = 0; } file.Close(); this.Cursor = Cursors.Default; }
/** * Description: * + Open file * */ private void openItem_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e) { StringBuilder imagePath = null; var openFile = new OpenFileDialog() { Title = "Open File Map", Multiselect = false, Filter = "Data file (.csv) |*.csv|All files (*.*)|*.*" }; var _Result = openFile.ShowDialog(); if (_Result == true) { if (openFile.CheckFileExists) { this.getListImagePath(); imagePath = new StringBuilder(openFile.FileName); System.IO.StreamReader readerFile = new System.IO.StreamReader(imagePath.ToString()); Image img; Rectangle rec; String data; String[] result; String iD; String imgPath; String imgID; int posCenterX; int posCenterY; int height; int width; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //readerFile.ReadLine(); while ((data = readerFile.ReadLine()) != null) { result = rgx.Split(data); if (result.Length >= 4) { iD = result[0]; imgID = result[1]; if (int.Parse(imgID.Trim()) > 700 && int.Parse(imgID.Trim()) <= 800) { posCenterX = int.Parse(result[2]); posCenterY = int.Parse(result[3]); height = int.Parse(result[4]); width = int.Parse(result[5]); rec = new Rectangle() { Height = height, Width = width, Tag = imgID, StrokeThickness = 2, Stroke = Brushes.White, Fill = new SolidColorBrush() }; this.drawRectangleToCanvas(rec, posCenterX - rec.Width / 2, cvMap.Height - (rec.Height / 2 + posCenterY)); } else { imgPath = listImagePath[imgID]; img = this.createImage(new BitmapImage(new Uri(imgPath, UriKind.RelativeOrAbsolute))); img.Tag = imgID; posCenterX = int.Parse(result[2]); posCenterY = int.Parse(result[3]); this.drawImageToCanvas(img, posCenterX - img.Source.Width / 2, cvMap.Height - (img.Source.Height / 2 + posCenterY)); } } } } } }
/** * * */ private void getListImagePath() { String filePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"File\Config.csv"); //String filePath = "pack://application:,,,/Mapeditor;component/File/Config.csv"; listImagePath = new Dictionary<string, string>(); System.IO.StreamReader readerFile = new System.IO.StreamReader(filePath); String data; String[] result; String imgID; String imgPath; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); readerFile.ReadLine(); while ((data = readerFile.ReadLine()) != null) { result = rgx.Split(data); if (result.Length >= 2) { imgID = result[0]; imgPath = result[1]; listImagePath.Add(imgID, imgPath); } } }
public static String[] Split(String Src, String SplitStr, System.Text.RegularExpressions.RegexOptions option) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(SplitStr, option); return reg.Split(Src); }
/// <summary> /// Loads the icons for the application /// </summary> /// <remarks> /// Sometimes, the program path can change and at this time, no icons /// are present /// </remarks> private void LoadIcons() { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("(\\\\)"); string[] s = r.Split(this.path); string newPath = ""; for (int j = 0; j < s.GetLength(0) - 3; j++) { newPath = newPath + s[j]; } Icon i; iconProvider = new Dictionary<string, Icon>(); //loading the program icon i = new Icon(newPath + "FerdaFrontEnd.ico"); iconProvider.Add("FerdaIcon", i); i = new Icon(newPath + "\\Icons\\Save project.ico"); iconProvider.Add("SaveAndQuitIcon", i); i = new Icon(newPath + "\\Icons\\Exit.ico"); iconProvider.Add("QuitWithoutSaveIcon", i); i = new Icon(newPath + "\\Icons\\New project.ico"); iconProvider.Add("NewIcon", i); i = new Icon(newPath + "\\Icons\\Delete from Desktop.ico"); iconProvider.Add("DeleteIcon", i); i = new Icon(newPath + "\\Icons\\Layout.ico"); iconProvider.Add("JoinIcon", i); i = new Icon(newPath + "\\Icons\\Rename Icon.ico"); iconProvider.Add("RenameIcon", i); i = new Icon(newPath + "\\Icons\\USerNote.ico"); iconProvider.Add("EditIcon", i); }
/// <summary> /// rfc 2047 header body decoding /// </summary> /// <param name="word"><c>string</c> to decode</param> /// <returns>the decoded <see cref="System.String" /></returns> public static String rfc2047decode(String word) { String[] words; String[] wordetails; System.Text.RegularExpressions.Regex rfc2047format = new System.Text.RegularExpressions.Regex(@"(=\?[\-a-zA-Z0-9]+\?[qQbB]\?[a-zA-Z0-9=_\-\.$%&/\'\\!:;{}\+\*\|@#~`^\(\)]+\?=)\s*", System.Text.RegularExpressions.RegexOptions.ECMAScript); // No rfc2047 format if (!rfc2047format.IsMatch(word)) { return word; } words = rfc2047format.Split(word); word = String.Empty; rfc2047format = new System.Text.RegularExpressions.Regex(@"=\?([\-a-zA-Z0-9]+)\?([qQbB])\?([a-zA-Z0-9=_\-\.$%&/\'\\!:;{}\+\*\|@#~`^\(\)]+)\?=", System.Text.RegularExpressions.RegexOptions.ECMAScript); for (int i = 0; i < words.GetLength(0); i++) { if (!rfc2047format.IsMatch(words[i])) { word += words[i]; continue; } wordetails = rfc2047format.Split(words[i]); switch (wordetails[2]) { case "q": case "Q": word += anmar.SharpMimeTools.SharpMimeTools.QuotedPrintable2Unicode(wordetails[1], wordetails[3]).Replace('_', ' '); ; break; case "b": case "B": try { Encoding enc = Encoding.GetEncoding(wordetails[1]); Byte[] ch = Convert.FromBase64String(wordetails[3]); word += enc.GetString(ch); } catch (Exception e) { Trace.Fail(e.Message, e.StackTrace); } break; default: break; } } return word; }
/// <summary> /// rfc 2047 header body decoding /// </summary> /// <param name="word"><c>string</c> to decode</param> /// <returns>the decoded <see cref="System.String" /></returns> public static System.String rfc2047decode( System.String word ) { System.String[] words; System.String[] wordetails; System.Text.RegularExpressions.Regex rfc2047format = new System.Text.RegularExpressions.Regex (@"(=\?[\-a-zA-Z0-9]+\?[qQbB]\?[a-zA-Z0-9=_\-\.$%&/\'\\!:;{}\+\*\|@#~`^]+\?=)\s*", System.Text.RegularExpressions.RegexOptions.ECMAScript); // No rfc2047 format if ( !rfc2047format.IsMatch (word) ){ #if LOG if ( log.IsDebugEnabled ) log.Debug ("Not a RFC 2047 string: " + word); #endif return word; } #if LOG if ( log.IsDebugEnabled ) log.Debug ("Decoding 2047 string: " + word); #endif words = rfc2047format.Split ( word ); word = System.String.Empty; rfc2047format = new System.Text.RegularExpressions.Regex (@"=\?([\-a-zA-Z0-9]+)\?([qQbB])\?([a-zA-Z0-9=_\-\.$%&/\'\\!:;{}\+\*\|@#~`^]+)\?=", System.Text.RegularExpressions.RegexOptions.ECMAScript); for ( int i=0; i<words.GetLength (0); i++ ) { if ( !rfc2047format.IsMatch (words[i]) ){ word += words[i]; continue; } wordetails = rfc2047format.Split ( words[i] ); switch (wordetails[2]) { case "q": case "Q": word += anmar.SharpMimeTools.SharpMimeTools.QuotedPrintable2Unicode ( wordetails[1], wordetails[3] ).Replace ('_', ' ');; break; case "b": case "B": try { System.Text.Encoding enc = System.Text.Encoding.GetEncoding (wordetails[1]); System.Byte[] ch = System.Convert.FromBase64String(wordetails[3]); word += enc.GetString (ch); } catch ( System.Exception ) { } break; } } #if LOG if ( log.IsDebugEnabled ) log.Debug ("Decoded 2047 string: " + word); #endif return word; }
public string[] GetParaHtml() // Only used by the articles system { string startTag = getDsiHtmlTag(); string endTag = "</dsi:html>"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\\n\\W*\\n"); string[] paraAry = r.Split(HtmlTextBox.Text); for (int i = 0; i < paraAry.Length; i++) { if (paraAry[i].Trim().Length == 0) paraAry[i] = ""; else { paraAry[i] = startTag + Cambro.Web.Helpers.CleanHtml(paraAry[i]) + endTag; } } return paraAry; }
public void StringsCanBeSplitUsingRegularExpressions() { var str = "the:rain:in:spain"; var regex = new System.Text.RegularExpressions.Regex(":"); string[] words = regex.Split(str); Assert.Equal(new[] { "the", "rain", "in", "spain" }, words); //A full treatment of regular expressions is beyond the scope //of this tutorial. The book "Mastering Regular Expressions" //is highly recommended to be on your bookshelf }
/// <summary> /// Arguments Parser Class. /// -- Parses Command Line Arguments passed to a Command Line application. /// -- Accepts the string array of arguments that was captured by the application /// at startup. /// -- Parameters should be prefixed with one of the following characters ("-", /// "--", "/", ":"). /// -- Calling Syntax: PDX.BTS.DataMaintenanceUtilites.ArgumentParser commandLine = new PDX.BTS.DataMaintenanceUtilities.ArgumentParser(args); /// - Returns a String Array of the Parameters with the parameter names as /// the array indices. /// - For example in the resulting array, the value for the Parameter /// "DataPath" (passed as /DataPath=C:\) will be obtained with - /// commandLine["DataPath"]. /// - For Boolean arguments. To determine if the parameter was passed is - /// "Usage" (passed as /Usage) will be determined by testing - /// if (commandLine["Usage"] == "true") /// </summary> // Constructor Method public ArgumentParser(string[] Args) { System.Text.RegularExpressions.Regex splitter = null; System.Text.RegularExpressions.Regex remover = null; string currentParameter = null; string[] parameterParts = null; try { // Instantiate a String Dictionary Object to hold the parameters that are found. _parsedParameters = new System.Collections.Specialized.StringDictionary(); // Set the Set of values that will be searched to find the parameter start // identifiers ("-", "--", "/", or ":"). splitter = new System.Text.RegularExpressions.Regex(@"^-{1,2}|^/|=|:", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled); // Set the Set of values that will be removed from the Parameters strings ("'", ".*"). remover = new System.Text.RegularExpressions.Regex(@"^['""]?(.*?)['""]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled); // Valid parameters forms: {-,/,--}param{ ,=,:}((",')value(",')) // Examples: -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (string currentTextString in Args) { // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) parameterParts = splitter.Split(currentTextString, 3); // Populate the String Dictionary Object with the values in the current parameter. switch (parameterParts.Length) { // Found a value (for the last parameter found (space separator)) case 1: if (currentParameter != null) { if (!_parsedParameters.ContainsKey(currentParameter)) { parameterParts[0] = remover.Replace(parameterParts[0], "$1"); _parsedParameters.Add(currentParameter, parameterParts[0]); } currentParameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no value, set it to true. if (currentParameter != null) { if (!_parsedParameters.ContainsKey(currentParameter)) { _parsedParameters.Add(currentParameter, "true"); } } currentParameter = parameterParts[1]; // Exit this case. break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if (currentParameter != null) { if (!_parsedParameters.ContainsKey(currentParameter)) { _parsedParameters.Add(currentParameter, "true"); } } currentParameter = parameterParts[1]; // Remove possible enclosing characters (",') if (!_parsedParameters.ContainsKey(currentParameter)) { parameterParts[2] = remover.Replace(parameterParts[2], "$1"); _parsedParameters.Add(currentParameter, parameterParts[2]); } currentParameter = null; // Exit this case. break; } } // In case a parameter is still waiting if (currentParameter != null) { if (!_parsedParameters.ContainsKey(currentParameter)) { _parsedParameters.Add(currentParameter, "true"); } } } catch { // Exit the method. return; } }
// Using the Compare function of IComparer public int Compare(object x, object y) { // Cast the objects to ListViewItems ListViewItem lvi1 = (ListViewItem)x; ListViewItem lvi2 = (ListViewItem)y; //try to convert to intervals first double first; double second; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("(^[<(]\\d+[;]\\d+[>)]$)"); System.Text.RegularExpressions.Regex r1 = new System.Text.RegularExpressions.Regex("[<>();]"); if ((r.IsMatch(lvi1.SubItems[column].Text)) && (r.IsMatch(lvi2.SubItems[column].Text))) { //hooray, an interval string[] numbers = r1.Split(lvi1.SubItems[column].Text); string[] numbers1 = r1.Split(lvi2.SubItems[column].Text); if ((numbers.Length > 1) && (numbers1.Length > 1) && (Double.TryParse(numbers[1], out first)) && (Double.TryParse(numbers1[1], out second))) { if (bAscending) return first > second ? 1 : (first < second ? -1 : 0); // Return the negated Compare return first > second ? -1 : (first < second ? 1 : 0); } else { //some strange string, this should not happen //if nothing works, it is a string string lvi1String = lvi1.SubItems[column].ToString(); string lvi2String = lvi2.SubItems[column].ToString(); // Return the normal Compare if (bAscending) return String.Compare(lvi1String, lvi2String); // Return the negated Compare return -String.Compare(lvi1String, lvi2String); } } else if ((Double.TryParse(lvi1.SubItems[column].Text, out first)) && (Double.TryParse(lvi2.SubItems[column].Text, out second))) { //it is double if (bAscending) return first > second ? 1 : (first < second ? -1 : 0); // Return the negated Compare return first > second ? -1 : (first < second ? 1 : 0); } else { //if nothing works, it is a string string lvi1String = lvi1.SubItems[column].ToString(); string lvi2String = lvi2.SubItems[column].ToString(); // Return the normal Compare if (bAscending) return String.Compare(lvi1String, lvi2String); // Return the negated Compare return -String.Compare(lvi1String, lvi2String); } // return 1; }
/// <summary> /// Sets the Passkey /// </summary> /// <param name="passkey">Passkey as a string</param> /// <returns>FS Response</returns> public byte ANTFS_SetPasskey(string passkey) { responseBuf.Clear(); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(","); String[] DataArray = regex.Split(passkey); int arraylength = DataArray.Length; byte[] passkeybytes = new byte[16]; for (int i = 0; i < arraylength; i++) passkeybytes[i] = System.Convert.ToByte(DataArray[i], 16); writeRawMessageToDevice(0xE2, new byte[] {0x34,0x01,passkeybytes[0],passkeybytes[1],passkeybytes[2],passkeybytes[3],passkeybytes[4],passkeybytes[5],passkeybytes[6], passkeybytes[7],passkeybytes[8],passkeybytes[9],passkeybytes[10],passkeybytes[11],passkeybytes[12],passkeybytes[13],passkeybytes[14],passkeybytes[15]}); return waitForMsg(new byte[] { 0xE0, 0x00, 0xE2, 0x34 })[0]; }
/// <summary> /// Loads the icons for the application /// </summary> /// <remarks> /// Sometimes, the program path can change and at this time, no icons /// are present /// </remarks> private void LoadIcons() { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("(\\\\)"); string[] s = r.Split(this.path); string newPath = ""; for (int j = 0; j < s.GetLength(0) - 3; j++) { newPath = newPath + s[j]; } Icon i; iconProvider = new Dictionary<string, Icon>(); //loading the program icon i = new Icon(newPath + "FerdaFrontEnd.ico"); iconProvider.Add("FerdaIcon", i); i = new Icon(newPath + "\\Icons\\Save project.ico"); iconProvider.Add("OkIcon", i); i = new Icon(newPath + "\\Icons\\Exit.ico"); iconProvider.Add("CancelIcon", i); i = new Icon(newPath + "\\Icons\\New project.ico"); iconProvider.Add("NewIcon", i); i = new Icon(newPath + "\\Icons\\Pack sockets.ico"); iconProvider.Add("TestIcon", i); }
///<summary> ///农历日期返回农历节日 ///农历节日如遇闰月,以第一个月为休假日,但如果闰12月,除夕则以闰月计 ///例如2009年闰5月 ///</summary> ///<returns></returns> public static string GetLunarFesitaval(DateTime datetime) { int lunaryear = cCalendar.GetYear(datetime); int lunarMonth = cCalendar.GetMonth(datetime); int lunarDay = cCalendar.GetDayOfMonth(datetime); int leapMonth = cCalendar.GetLeapMonth(lunaryear); bool isleap = false; if (leapMonth > 0) { if (leapMonth == lunarMonth) { //闰月 isleap = true; lunarMonth--; } else if (lunarMonth > leapMonth) { lunarMonth--; } } string str = @"(\d{2})(\d{2})([\s\*])(.+)$"; //匹配的正则表达式 System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(str); for (int i = 0; i < lFtv.Length; i++) { string[] s = re.Split(lFtv[i]); //农历节日如遇闰月,以第一个月为休假日,闰月的节日不算 if (!isleap && Convert.ToInt32(s[1]) == lunarMonth && Convert.ToInt32(s[2]) == lunarDay) { return s[4]; } } return ""; }