public Replace ( string input, System evaluator ) : string | ||
input | string | |
evaluator | System | |
return | string |
/// <summary/> protected CodeFormat() { //generate the keyword and preprocessor regexes from the keyword lists var r = new Regex(@"\w+|-\w+|#\w+|@@\w+|#(?:\\(?:s|w)(?:\*|\+)?\w+)+|@\\w\*+"); string regKeyword = r.Replace(Keywords, @"(?<=^|\W)$0(?=\W)"); string regPreproc = r.Replace(Preprocessors, @"(?<=^|\s)$0(?=\s|$)"); r = new Regex(@" +"); regKeyword = r.Replace(regKeyword, @"|"); regPreproc = r.Replace(regPreproc, @"|"); if (regPreproc.Length == 0) { regPreproc = "(?!.*)_{37}(?<!.*)"; //use something quite impossible... } //build a master regex with capturing groups var regAll = new StringBuilder(); regAll.Append("("); regAll.Append(CommentRegex); regAll.Append(")|("); regAll.Append(StringRegex); if (regPreproc.Length > 0) { regAll.Append(")|("); regAll.Append(regPreproc); } regAll.Append(")|("); regAll.Append(regKeyword); regAll.Append(")"); RegexOptions caseInsensitive = CaseSensitive ? 0 : RegexOptions.IgnoreCase; CodeRegex = new Regex(regAll.ToString(), RegexOptions.Singleline | caseInsensitive); }
public Date(string data) { if (!data.Equals("NOTSET")) { try { Regex rgx = new Regex("[^a-zA-Z0-9 -]"); string[] pole = data.Split('|'); Year = int.Parse(rgx.Replace(pole[0], "")); Month = int.Parse(rgx.Replace(pole[1], "")); Day = int.Parse(rgx.Replace(pole[2], "")); } catch (Exception e) { MessageBox.Show("Something wen wrong date was --> " + data + "\n Exception is " + e.Message); Year = 0; Month = 0; Day = 0; } } else { Year = 0; Month = 0; Day = 0; } }
public void NewTestRequest_WithSubjectAndBody_ShouldOutputInCorrectFormat() { const string xml = @"<test_set> <applications type=""array""> <application> <code>outlookcom</code> </application> <application> <code>gmailnew</code> </application> <application> <code>notes8</code> </application> </applications> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> <email_source> <body><![CDATA[<html><body><p>Here is an email body!</p></body></html>]]></body> <subject>My test email to Litmus</subject> </email_source> </test_set>"; var emailClients = new List<TestingApplication>(); emailClients.Add(new TestingApplication() { ApplicationCode = "outlookcom", ResultType = "email" }); emailClients.Add(new TestingApplication() { ApplicationCode = "gmailnew", ResultType = "email" }); emailClients.Add(new TestingApplication() { ApplicationCode = "notes8", ResultType = "email" }); var request = new CreateEmailTestRequest(emailClients, "My test email to Litmus", "<html><body><p>Here is an email body!</p></body></html>"); var cleanSpacing = new Regex(@"\s+", RegexOptions.None); var cleanRequest = cleanSpacing.Replace(request.ToString(), ""); var cleanXml = cleanSpacing.Replace(xml, ""); Console.WriteLine(cleanRequest); Console.WriteLine(cleanXml); Assert.That(cleanRequest == cleanXml); }
public void NewTestRequest_WithOnlyTestingApplications_ShouldOutputInCorrectFormat() { const string xml = @"<test_set> <applications type=""array""> <application> <code>outlookcom</code> </application> <application> <code>gmailnew</code> </application> <application> <code>notes8</code> </application> </applications> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> </test_set>"; var emailClients = new List<TestingApplication>(); emailClients.Add(new TestingApplication(){ApplicationCode = "outlookcom",ResultType = "email"}); emailClients.Add(new TestingApplication() {ApplicationCode = "gmailnew", ResultType = "email"}); emailClients.Add(new TestingApplication() {ApplicationCode = "notes8", ResultType = "email"}); var request = new CreateEmailTestRequest(emailClients); var cleanSpacing = new Regex(@"\s+", RegexOptions.None); var cleanRequest = cleanSpacing.Replace(request.ToString(), ""); var cleanXml = cleanSpacing.Replace(xml, ""); Assert.That(cleanRequest == cleanXml); }
public static string FormatAlter(string ObjectType, string body, ISchemaBase item, Boolean quitSchemaBinding) { string prevText = null; try { prevText = (string)body.Clone(); SearchItem sitem = FindCreate(ObjectType, item, prevText); Regex regAlter = new Regex("CREATE"); if (!quitSchemaBinding) return regAlter.Replace(sitem.Body, "ALTER", 1, sitem.FindPosition); //return prevText.Substring(0, iFind) + "ALTER " + sitem.ObjectType + " " + prevText.Substring(iFind + sitem.ObjectType.Length + 7, prevText.Length - (iFind + sitem.ObjectType.Length + 7)).TrimStart(); else { string text = regAlter.Replace(sitem.Body, "ALTER", 1, sitem.FindPosition); Regex regex = new Regex("WITH SCHEMABINDING", RegexOptions.IgnoreCase); return regex.Replace(text, ""); } //return ""; } catch { return prevText; } }
private void DoDeleteWordInBrackets(Word word) { var regex = new Regex(@"\(.*\)"); word.BaseWord = regex.Replace(word.BaseWord, string.Empty); word.Translation = regex.Replace(word.Translation, string.Empty); }
private static string m_StrOperationFormatRegEx = @"(\)\s*[-+/*])\s*(\()";//скобки рядом с арифметической операцией в весовой части /// <summary> /// Форматировать. /// </summary> /// <param name="strUpdateCmd"></param> /// <returns></returns> public static string Format(string strUpdateCmd) { //Пока распознает не все возможные варианты текста команды обновления, форматирует не идеально, но приемлемо //Сделать 1 рег. выражением нет смысла: 1. Выражение будет оч. сложное 2.Будет очень долго работать //(десятки секунд +, а надо формат-ть практически "на лету" при выводе куда-то ) string strFormmattedCmd = String.Empty; Regex regEx = new Regex(m_Str1stFormatStepRegEx, RegexOptions.IgnoreCase); //1 совпадение - вся строка, разбитая на именованые группы, которые представляют собой основные куски запроса GroupCollection grpCol = regEx.Match(strUpdateCmd).Groups; //Форматирование координат Tuple СЛЕВА от знака присваивания в SET regEx = new Regex(m_StrTupleAndValueFormatRegEx, RegexOptions.IgnoreCase); string strTuple = regEx.Replace(grpCol["TuplePart"].Value, Environment.NewLine + "$1"); //Форматирование координат Tuple СПРАВА от знака присваивания в SET string strValue = regEx.Replace(grpCol["ValuePart"].Value, "$1" + Environment.NewLine); string strWeight = String.Empty; if (grpCol["WeightPart"].Value != null && grpCol["WeightPart"].Value != String.Empty)//Если есть весовая часть { //Форматирование веса с учетом того, что могут попадаться вызовы ф-ций regEx = new Regex(m_StrWeightFormatRegEx, RegexOptions.IgnoreCase); strWeight = regEx.Replace(grpCol["WeightPart"].Value, "$1" + Environment.NewLine); //Форматирование арифметич операций в весе, если есть regEx = new Regex(m_StrOperationFormatRegEx, RegexOptions.IgnoreCase); strWeight = regEx.Replace(strWeight, String.Format("$1{0}$2{0}", Environment.NewLine)); } strFormmattedCmd = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{7}{0}{8}{0}{9}", Environment.NewLine, grpCol["UpdatePart"].Value, grpCol["SetPart"].Value, strTuple, grpCol["EqualPart"].Value, strValue, grpCol["UsePart"].Value, grpCol["ByPart"].Value, strWeight, grpCol["EndParenthesis"].Value); return strFormmattedCmd; }
//+ボタンが押されたときに追加 private void Add_log_button_Click(object sender,EventArgs e) { if(Browser.Url != null) { string url = Browser.Url.ToString(); string name = Browser.DocumentTitle; Regex remove_protocol_name = new Regex("^https?://"); Regex remove_wiki_link = new Regex("#.+$"); Regex remove_kotobank_id = new Regex(@"-\d+?$"); for(int i = 0;i < slist.Rows.Count;i++) { DataRow site = slist.Rows[i]; string match_chk_str = site["match_str"].ToString(); if(match_chk_str != "") { if(url.Contains(match_chk_str)) { string s_str = url; s_str = remove_protocol_name.Replace(s_str,""); s_str = s_str.Replace(match_chk_str,""); if(site["site_name"].ToString() == "Wikipedia" || site["site_name"].ToString() == "Uncyclopedia") { s_str = remove_wiki_link.Replace(s_str,""); url = remove_wiki_link.Replace(url,""); }else if(site["site_name"].ToString() == "コトバンク") { s_str = remove_wiki_link.Replace(s_str,""); s_str = remove_kotobank_id.Replace(s_str,""); url = remove_wiki_link.Replace(url,""); } name = site["site_sname"] + " " + s_str; } } } add_log(url,name); } }
private void Application_BeginRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; foreach (var rule in GetRuleList()) { var lookFor = "^" + ResolveUrl(app.Request.ApplicationPath, rule.LookFor) + "$"; var re = new Regex(lookFor, RegexOptions.IgnoreCase); if (IsHttpUrl(rule.LookFor)) { if (re.IsMatch(app.Request.Url.AbsoluteUri)) { var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Url.AbsoluteUri, rule.SendTo)); RewritePath(app.Context, sendTo); break; } } else { if (re.IsMatch(app.Request.Path)) { var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Path, rule.SendTo)); RewritePath(app.Context, sendTo); break; } } } }
public void ShouldNotRemoveLineBreaksFromSqlQueries() { using (var spy = new SqlLogSpy()) using (var s = OpenSession()) using (var t = s.BeginTransaction()) { const string sql = @" select Id from Entity where 1=1"; var query = s.CreateSQLQuery(sql); Assert.DoesNotThrow(() => query.List()); string renderedSql = spy.Appender.GetEvents()[0].RenderedMessage; Regex whitespaces = new Regex(@"\s+", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); Assert.AreEqual( string.Compare( whitespaces.Replace(sql, " ").Trim(), whitespaces.Replace(renderedSql, " ").Trim(), true ), 0 ); } }
internal bool Save(string name, string output, bool withSample =true) { WithSample = withSample; int index = name.LastIndexOf('\\'); OrgFilename = name.Substring(index + 1, name.LastIndexOf('.') - index - 1); Dir = output; OrgDir = name.Substring(0, index + 1); // with \\ Regex reg = new Regex(@"[\\/\:\*\?\<\>\|\\""]"); Artist = reg.Replace(Artist, ""); Title = reg.Replace(Title, ""); Diff = reg.Replace(Diff, ""); Filename = string.Format("{0} - {1} ({2}) [{3}].osu", Artist, Title, "BMXC_V1", Diff); if(File.Exists(Dir+Filename)) Filename = "("+OrgFilename+")"+Filename; //no notes in special column, convert to normal map. if (!Special) { Column--; } doSort(); calculateTime(); if(withSample) calculateEvent(); calculateNote(); writeToFile(); return true; }
public string GetJson(DataSet ds) { StringBuilder json = new StringBuilder(); json.Append("{"); Regex regComma = new Regex(@"\,$"); string tempString = ""; foreach (DataTable dt in ds.Tables) { json.Append("\"" + dt.TableName + "\":["); foreach (DataRow dr in dt.Rows) { json.Append("{"); for (int i = 0; i < dt.Columns.Count; i++) { if (i > 0) { json.Append(","); } json.Append("\"" + dt.Columns[i].ColumnName + "\":\"" + replaceSpicalCharacter(Convert.ToString(dr[i])) + "\""); } json.Append("},"); } tempString = regComma.Replace(json.ToString(),""); json.Length = 0; json.Append(tempString); json.Append("],"); } tempString = regComma.Replace(json.ToString(), ""); json.Length = 0; json.Append(tempString); json.Append("}"); return json.ToString(); }
public List<Tuple<double, double>> GetSpeedByNoise(StreamReader fs) { List<string> strs = new List<string>(); Regex dataRegex = new Regex(@"y = \d"); while (!fs.EndOfStream) { var str = fs.ReadLine(); if (dataRegex.IsMatch(str)) { strs.Add(str); } } var velocAndNoise = new List<Tuple<double, double>>(strs.Count); Regex notNumbers = new Regex(@"[A-Za-z]"); Regex dotRegex = new Regex(@"\."); for (int i = 0; i < strs.Count; i++) { string veloc = dotRegex.Replace(notNumbers.Replace(strs[i].Split('=')[1], ""), ","); string noise = dotRegex.Replace(notNumbers.Replace(strs[i].Split('=')[2], ""), ","); velocAndNoise.Add(new Tuple<double, double>(Convert.ToDouble(noise), Convert.ToDouble(veloc))); } fs.BaseStream.Seek(0, SeekOrigin.Begin); return velocAndNoise; }
public void NewTestRequest_WithUrl_ShouldOutputInCorrectFormat() { const string xml = @"<test_set> <applications type=""array""> <application> <code>chrome2</code> </application> <application> <code>ie7</code> </application> <application> <code>ie6</code> </application> </applications> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> <url>http://google.com</url> </test_set>"; var pageClients = new List<TestingApplication>(); pageClients.Add(new TestingApplication(){ApplicationCode = "chrome2",ResultType = "page"}); pageClients.Add(new TestingApplication() {ApplicationCode = "ie7", ResultType = "page"}); pageClients.Add(new TestingApplication() {ApplicationCode = "ie6", ResultType = "page"}); var request = new CreatePageTestRequest(pageClients, "http://google.com"); var cleanSpacing = new Regex(@"\s+", RegexOptions.None); var cleanRequest = cleanSpacing.Replace(request.ToString(), ""); var cleanXml = cleanSpacing.Replace(xml, ""); Console.WriteLine(cleanRequest); Console.WriteLine(cleanXml); Assert.That(cleanRequest == cleanXml); }
/// <summary> /// INTERNAL /// </summary> /// <param name="error">The exception to format.</param> public static string FormatException(Exception error) { if (error == null) throw new ArgumentNullException("error"); //?? _090901_055134 Regex is used to fix bad PS V1 strings; check V2 Regex re = new Regex("[\r\n]+"); string info = error.GetType().Name + ":" + Environment.NewLine + re.Replace(error.Message, Environment.NewLine) + Environment.NewLine; // get an error record if (error.GetType().FullName.StartsWith("System.Management.Automation.", StringComparison.Ordinal)) { object errorRecord = GetPropertyValue(error, "ErrorRecord"); if (errorRecord != null) { // process the error record object ii = GetPropertyValue(errorRecord, "InvocationInfo"); if (ii != null) { object pm = GetPropertyValue(ii, "PositionMessage"); if (pm != null) //?? 090517 Added Trim(), because a position message starts with an empty line info += re.Replace(pm.ToString().Trim(), Environment.NewLine) + Environment.NewLine; } } } if (error.InnerException != null) info += Environment.NewLine + FormatException(error.InnerException); return info; }
/// <summary> /// This method parses a friendly Derived Columns expression entered by the user into a Lineage-ID based /// expression which is required by SSIS, using a regular-expression based parser. /// Additionally, it will set the Input Column Usage for any columns found in the expression. /// </summary> /// <param name="expression">Expression to be parsed.</param> /// <param name="transformation">Transformation to use for evaluating the lineage IDs</param> /// <param name="vi">Transformation Virtual Input used to search for input columns.</param> /// <param name="inputColumnUsageType">DTSUsageType for columns mapped in this expression.</param> /// <returns>Expression struct with the pre-processed and post-processed expression.</returns> public static Expression ExpressionCleanerAndInputMapBuilder(string expression, Transformation transformation, IDTSVirtualInput100 vi, DTSUsageType inputColumnUsageType) { Expression exp = new Expression(); exp.OriginalExpression = expression; exp.ProcessedExpression = expression; exp.FriendlyExpression = expression; exp.ContainsId = false; foreach (IDTSVirtualInputColumn100 vcol in vi.VirtualInputColumnCollection) { string regexString = String.Format(CultureInfo.CurrentCulture, "(\"(?:[^\"]|(?<=\\\\)\")*\")|(?<vCol>(?<!@\\[?|:)\\[?\\b{0}\\b\\]?)", Regex.Escape(vcol.Name)); var regex = new Regex(regexString, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); int groupNumber = regex.GroupNumberFromName("vCol"); var processedEme = new ExpressionMatchEvaluatorStruct(groupNumber, "#" + vcol.LineageID, transformation, vi, inputColumnUsageType, vcol); var friendlyEme = new ExpressionMatchEvaluatorStruct(groupNumber, vcol.Name, null, null, DTSUsageType.UT_IGNORED, null); exp.ProcessedExpression = regex.Replace(exp.ProcessedExpression, new MatchEvaluator(processedEme.EvaluateMatch)); exp.FriendlyExpression = regex.Replace(exp.FriendlyExpression, new MatchEvaluator(friendlyEme.EvaluateMatch)); } if (exp.ProcessedExpression != exp.OriginalExpression) { exp.ContainsId = true; } return exp; }
private void button1_Click(object sender, EventArgs e) { //Apply Regex replacer = new Regex(textBox1.Text); foreach (var node in nodes) node.node_name = replacer.Replace(node.node_name, textBox2.Text); //Update visual list for (int i = 0; i < list_box.Items.Count; i++) { var nd = list_box.Items[i]; list_box.Items.RemoveAt(i); list_box.Items.Insert(i, nd); } //Refactoring names in lists foreach (node_info node in node_gen.all_nodes) { foreach (var subnode in node.subnodes) { if (subnode is extended_simple_element) { extended_simple_element sn = (subnode as extended_simple_element); string list_type = sn.list_type; if (list_type != "") sn.list_type = replacer.Replace(list_type, textBox2.Text); } } } }
private static string handleReversing(string input) { string result = input; string pattern = @"\b([A-Z\d]+)\b"; string magicalPattern = "IHATEREGEX"; Regex rageEscalator = new Regex(magicalPattern); List<string> upperCaseWords = Regex.Matches(result, pattern).Cast<Match>().Select(match => match.Value).ToList(); result = Regex.Replace(result, pattern, magicalPattern); // Replace matches with aptly named placeholders. foreach (var word in upperCaseWords) { // http://stackoverflow.com/questions/1540620/check-if-a-string-has-at-least-one-number-in-it-using-linq if (isPalindrome(word)) { result = rageEscalator.Replace(result, doubleLetters(word), 1); } else { result = rageEscalator.Replace(result, reverseString(word), 1); } } return result; }
private List<SiteCoord> SiteList(string searchString) { //Return value List<SiteCoord> results = new List<SiteCoord>(); //Regex for site name Regex rgx = new Regex("[^a-zA-Z0-9]"); //Read RVSite available var _sites = sites.GetAll(); //Remove characters from search string searchString = rgx.Replace(searchString, "").ToUpper(); if (searchString != null) { //Filter by RV Site foreach (var _site in _sites) { string rvsiteShort = rgx.Replace(_site.RVSite, "").ToUpper(); if (rvsiteShort.Contains(searchString)) { results.Add(new SiteCoord(_site.id, _site.RVSite, _site.latitude, _site.longitude)); } } } return results.OrderBy(q => q.Label).ToList(); }
static int Main(string[] args) { try { if (args.Length < 2 || args.Length == 1 && (args[0] == "/?" || args[0] == "-?")) { ShowHelp(); return 0; } string templateFile = args[0]; string outFile = args[1]; StreamReader stream = new StreamReader(templateFile); string fileContents = stream.ReadToEnd(); stream.Close(); Regex regex = new Regex("\\$YEAR"); fileContents = regex.Replace(fileContents, DateTime.Now.Year.ToString()); regex = new Regex("\\$MONTH"); fileContents = regex.Replace(fileContents, string.Format("{0:MM}", DateTime.Now)); regex = new Regex("\\$DAY"); fileContents = regex.Replace(fileContents, string.Format("{0:dd}", DateTime.Now)); regex = new Regex("\\$!((?<env>\\w+)|\\{(?<env>\\w+):(?<default>\\w+)\\})"); Match match = regex.Match(fileContents); while (match.Success) { string strEnv = match.Result("${env}"); string strDefault = match.Result("${default}"); string strEnvValue = Environment.GetEnvironmentVariable(strEnv); if (strEnvValue != null && strEnvValue != string.Empty) fileContents = regex.Replace(fileContents, strEnvValue, 1, match.Index); else fileContents = regex.Replace(fileContents, strDefault, 1, match.Index); match = regex.Match(fileContents); } fileContents = string.Format("// This file is generated from {0}. Do NOT modify!\n{1}", Path.GetFileName(templateFile), fileContents); StreamWriter outStream = new StreamWriter(outFile); outStream.Write(fileContents); outStream.Close(); } catch(Exception e) { System.Console.WriteLine("Internal program error in program {0}", e.Source); System.Console.WriteLine("\nDetails:\n{0}\nin method {1}.{2}\nStack trace:\n{3}", e.Message, e.TargetSite.DeclaringType.Name, e.TargetSite.Name, e.StackTrace); return 1; } return 0; }
/// <summary> /// Constructor. /// Parameter format: {/,-,--}argname{ ,=,:}((",')value(",')). Examples: /arg3:"any-:-text" -arg1 value1 --arg2 /arg4=text -arg5 'any text' /// </summary> /// <param name="args">Command line parameters</param> public CommandLineArguments(string[] args) { _parameters = new Dictionary<string, string>(); Regex spliterRegex = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex removerRegex = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string parameter = null; string[] parts; foreach (string arg in args) { // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) parts = spliterRegex.Split(arg, 3); switch (parts.Length) { case 1: // Found a value (for the last parameter found (space separator)) if (parameter != null) { if (!_parameters.ContainsKey(parameter)) { parts[0] = removerRegex.Replace(parts[0], "$1"); _parameters.Add(parameter, parts[0]); } parameter = null; } // else Error: no parameter waiting for a value (skipped) break; case 2: // Found just a parameter // The last parameter is still waiting. With no value, set it to true. if (parameter != null) { if (!_parameters.ContainsKey(parameter)) _parameters.Add(parameter, "true"); } parameter = parts[1]; break; case 3: // Parameter with enclosed value // The last parameter is still waiting. With no value, set it to true. if (parameter != null) if (!_parameters.ContainsKey(parameter)) _parameters.Add(parameter, "true"); parameter = parts[1]; // Remove possible enclosing characters (",') if (!_parameters.ContainsKey(parameter)) { parts[2] = removerRegex.Replace(parts[2], "$1"); _parameters.Add(parameter, parts[2]); } parameter = null; break; } } // In case a parameter is still waiting if (parameter != null) if (!_parameters.ContainsKey(parameter)) _parameters.Add(parameter, "true"); }
static void ContainsExcludingWhitespace(string haystack, string needle) { var ws = new Regex(@"\s+"); var spacifiedHaystack = ws.Replace(haystack, " "); var spacifiedNeedle = ws.Replace(needle, " "); Assert.That(spacifiedHaystack, Is.StringContaining(spacifiedNeedle)); }
public void TestForReplace() { const string s = "Select * from User where Age > ? And Age < ?"; const string exp = "Select * from User where Age > @p0 And Age < @p1"; var reg = new Regex("\\?"); string act = reg.Replace(s, "@p0", 1); act = reg.Replace(act, "@p1", 1); Assert.AreEqual(exp, act); }
Fraction RemoveCommonDigits(Fraction fraction) { var commonDigit = FindCommonDigit(fraction); var regex = new Regex(commonDigit.ToString()); var modifiedNumerator = regex.Replace(fraction.Numerator.ToString(), string.Empty, 1); var modifiedDenominator = regex.Replace(fraction.Denominator.ToString(), string.Empty, 1); return new Fraction(int.Parse(modifiedNumerator), int.Parse(modifiedDenominator)); }
public Arguments(string[] args) { _params = new StringDictionary(); Regex spliter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string parm = null; string[] parts; foreach (var a in args) { parts = spliter.Split(a, 3); switch (parts.Length) { case 1: if (parm != null) { if (!_params.ContainsKey(parm)) { parts[0] = remover.Replace(parts[0], "$1"); _params.Add(parm, parts[0]); } parm = null; } break; case 2: if (parm != null) { if (!_params.ContainsKey(parm)) _params.Add(parm, "true"); } parm = parts[1]; break; case 3: if (parm != null) { if (!_params.ContainsKey(parm)) _params.Add(parm, "true"); } parm = parts[1]; if (!_params.ContainsKey(parm)) { parts[2] = remover.Replace(parts[2], "$1"); _params.Add(parm, parts[2]); } parm = null; break; } } if (parm != null) { if (!_params.ContainsKey(parm)) _params.Add(parm, "true"); } }
static void Main(string[] args) { string input = Console.ReadLine(); Regex regex = new Regex(@"(\w)\1+"); string replacement = "$1$1"; string res = regex.Replace(input, replacement); replacement = "$1"; res = regex.Replace(input, replacement); Console.WriteLine(res); }
/// <summary> /// Determines if the given version is the same as the version in this update info. /// </summary> /// <param name="p_strVersion">The version to match.</param> /// <returns><c>true</c> if the given version is the same as the version in this update info; /// <c>false</c> otherwise.</returns> public bool IsMatchingVersion(string p_strVersion) { Regex rgxClean = new Regex(@"([v(ver)]\.?)|((\.0)+$)", RegexOptions.IgnoreCase); string strThisVersion = rgxClean.Replace(NewestInfo.HumanReadableVersion ?? "", ""); string strThatVersion = rgxClean.Replace(p_strVersion ?? "", ""); if (String.IsNullOrEmpty(strThisVersion) || string.IsNullOrEmpty(strThatVersion)) return true; else return String.Equals(strThisVersion, strThatVersion, StringComparison.OrdinalIgnoreCase); }
/// <summary> /// Helper function that takes an organization/company name, application name, and application version string /// and returns the canonicalized form that can be used as the origin parameter in Cloud API requests. /// </summary> /// <param name="organization">The name of the organization/company that created the software using the /// .NET Cloud library.</param> /// <param name="applicationName">The name of the application.</param> /// <param name="applicationVersion">The application version string.</param> /// <returns></returns> public static string GetCanonicalOriginString(string organization, string applicationName, string applicationVersion) { Regex nameRegex = new Regex("[^a-z0-9]"); Regex versionRegex = new Regex("[^\\w\\.\\-]"); string organizationComponent = nameRegex.Replace(organization.ToLower(), string.Empty); string applicationComponent = nameRegex.Replace(applicationName.ToLower(), string.Empty); string versionComponent = versionRegex.Replace(applicationVersion.ToLower(), string.Empty); return string.Format("{0}.{1}.{2}", organizationComponent, applicationComponent, versionComponent); }
// Constructor public Arguments(string[] Args) { Parameters=new StringDictionary(); Regex Spliter=new Regex(@"^-{1,2}|^/|=|:",RegexOptions.IgnoreCase|RegexOptions.Compiled); Regex Remover= new Regex(@"^['""]?(.*?)['""]?$",RegexOptions.IgnoreCase|RegexOptions.Compiled); string Parameter=null; string[] Parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--' foreach(string Txt in Args){ // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) Parts=Spliter.Split(Txt,3); switch(Parts.Length){ // Found a value (for the last parameter found (space separator)) case 1: if(Parameter!=null){ if(!Parameters.ContainsKey(Parameter)){ Parts[0]=Remover.Replace(Parts[0],"$1"); Parameters.Add(Parameter,Parts[0]); } Parameter=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(Parameter!=null){ if(!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter,"true"); } Parameter=Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if(Parameter!=null){ if(!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter,"true"); } Parameter=Parts[1]; // Remove possible enclosing characters (",') if(!Parameters.ContainsKey(Parameter)){ Parts[2]=Remover.Replace(Parts[2],"$1"); Parameters.Add(Parameter,Parts[2]); } Parameter=null; break; } } // In case a parameter is still waiting if(Parameter!=null){ if(!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter,"true"); } }
public static void BroadCastData(object target, Stream outgoingData) { Log.Configure("LINQBridgeVs", "DynamicCore"); try { var targetType = GetInterfaceTypeIfIsIterator(target); var targetTypeFullName = TypeNameHelper.GetDisplayName(targetType, true); var targetTypeName = TypeNameHelper.GetDisplayName(targetType, false); //I'm lazy I know it... var pattern1 = new Regex("[<]"); var pattern2 = new Regex("[>]"); var pattern3 = new Regex("[,]"); var pattern4 = new Regex("[`]"); var pattern5 = new Regex("[ ]"); var fileName = pattern1.Replace(targetTypeFullName, "("); fileName = pattern2.Replace(fileName, ")"); var typeName = pattern1.Replace(targetTypeName, string.Empty); typeName = pattern2.Replace(typeName, string.Empty); typeName = pattern3.Replace(typeName, string.Empty); typeName = pattern4.Replace(typeName, string.Empty); typeName = pattern5.Replace(typeName, string.Empty); fileName = TypeNameHelper.RemoveSystemNamespaces(fileName); var message = new Message { FileName = string.Format(FileNameFormat, fileName), TypeName = typeName.Trim(), TypeFullName = targetTypeFullName, //TypeLocation = GetAssemblyLocation(vsVersion, targetType.Name), TypeNamespace = targetType.Namespace, AssemblyQualifiedName = targetType.AssemblyQualifiedName }; var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(outgoingData, message); Log.Write("BroadCastData to LINQBridgeVsTruck"); var truck = new Truck("LINQBridgeVsTruck"); truck.LoadCargo(target); var res = truck.DeliverTo(typeName); Log.Write("Data Succesfully Shipped to Grapple"); } catch (Exception e) { Log.Write(e, "Error in BroadCastData"); } }
public static string NormalizeURL(this string s) { //tolower breaks youtube // s = s.ToLower(); System.Text.RegularExpressions.Regex r = new Text.RegularExpressions.Regex("\\s"); s = r.Replace(s, ""); return(s); }
public void SetText(string newText) { _settingText = true; BeginUpdate(); try { Document.TextContent = _repairCRLF.Replace(newText, "\r\n"); Document.UndoStack.ClearAll(); Document.BookmarkManager.Clear(); Document.UpdateQueue.Clear(); ActiveTextAreaControl.Caret.Position = TextLocation.Empty; ActiveTextAreaControl.ScrollToCaret(); } finally { _settingText = false; EndUpdate(); } Refresh(); // if this isn't done then half the loaded text won't show up. }
/// <summary> /// 格式化文本(防止SQL注入) /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Formatstr(string html) { System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex10.Replace(html, "s_elect"); html = regex11.Replace(html, "u_pudate"); html = regex12.Replace(html, "d_elete"); html = html.Replace("'", "’"); html = html.Replace(" ", " "); return(html); }
// Chuyển tiếng việt có dấu thành không dấu #region convert tieng viet ko dau public static string ConvertToUnSign(string text) { if (text != null) { for (int i = 33; i < 48; i++) { text = text.Replace(((char)i).ToString(), ""); } for (int i = 58; i < 65; i++) { text = text.Replace(((char)i).ToString(), ""); } for (int i = 91; i < 97; i++) { text = text.Replace(((char)i).ToString(), ""); } for (int i = 123; i < 127; i++) { text = text.Replace(((char)i).ToString(), ""); } } else { text = ""; } //text = text.Replace(" ", "-"); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\p{IsCombiningDiacriticalMarks}+"); string strFormD = text.Normalize(System.Text.NormalizationForm.FormD); return(regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D')); }
/// <summary> /// 取出含html語法中只有文字的部份 /// </summary> /// <param name="p"></param> /// <returns></returns> public static string FilterHtml(string html) { if (!string.IsNullOrEmpty(html)) { //html = Regex.Replace(p, "<[^>]+>", ""); //return p; System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"<style[\s\S]+</style *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex10.Replace(html, ""); //过滤<style></style>标记 html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤img html = regex7.Replace(html, ""); //过滤p html = regex8.Replace(html, ""); //过滤p html = regex9.Replace(html, ""); html = html.Replace(" ", ""); html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); html = html.Replace("; ", ""); html = html.Replace(" ", ""); html = html.Replace("&", ""); html = html.Replace("nbsp;", ""); return(html.Trim()); } else { return(string.Empty); } }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { var NIF = value as string; if (NIF != null) { string patron = "[A-HJ-NP-SUVW][0-9]{7}[0-9A-J]|\\d{8}[TRWAGMYFPDXBNJZSQVHLCKE]|[X]\\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]|[X]\\d{8}[TRWAGMYFPDXBNJZSQVHLCKE]|[YZ]\\d{0,7}[TRWAGMYFPDXBNJZSQVHLCKE]"; string sRemp = ""; bool ret = false; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(patron); sRemp = rgx.Replace(NIF.ToString(), "OK"); if (sRemp == "OK") { ret = true; } if (ret) { return(new ValidationResult(true, null)); } } return(new ValidationResult(false, null)); }
/// <summary> /// 清除文本中的HTML格式 /// </summary> /// <param name="strHtml"></param> /// <returns></returns> public static string StripHTML(string strHtml) { if (string.IsNullOrEmpty(strHtml)) { return(""); } //过滤脚本及其内容 System.Text.RegularExpressions.Regex regexScript = new System.Text.RegularExpressions.Regex(@"<[\s]*?script[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?script[\s]*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //过滤CSS样式及其内容 System.Text.RegularExpressions.Regex regexStyle = new System.Text.RegularExpressions.Regex(@"<[\s]*?style[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?style[\s]*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //过滤所有<>内的内容 System.Text.RegularExpressions.Regex regexTag = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); strHtml = regexScript.Replace(strHtml, ""); strHtml = regexStyle.Replace(strHtml, ""); strHtml = regexTag.Replace(strHtml, ""); strHtml = strHtml.Replace("<", "<"); strHtml = strHtml.Replace(">", ">"); return(strHtml); }
public static string FromJSONString(string src) { StringBuilder sb = new StringBuilder(src); sb.Replace("\\\\", "\\"); sb.Replace("\\\"", "\""); sb.Replace("\\/", "/"); sb.Replace("\\b", "\b"); sb.Replace("\\f", "\f"); sb.Replace("\\n", "\n"); sb.Replace("\\r", "\r"); sb.Replace("\\t", "\t"); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\\u[0-9a-fA-F]{4}"); return(reg.Replace(sb.ToString(), match => { var str = match.Value.Substring(2, 4); int n = int.Parse(str, System.Globalization.NumberStyles.HexNumber); char c = (char)n; return c.ToString(); })); }
/// <summary> /// 从字符串中移除html标签 /// </summary> /// <param name="o"></param> /// <returns></returns> public static string Removehtml(object o) { if (o == null) { return(""); } if (string.IsNullOrEmpty(o.ToString())) { return(""); } var reg = new System.Text.RegularExpressions.Regex("<.*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.Multiline); return(new System.Text.RegularExpressions.Regex("\\s+").Replace( reg.Replace(o.ToString(), "") .Replace(System.Environment.NewLine, "") .Replace((char)10, (char)0) .Replace((char)13, (char)0) , " ").Replace(" ", "").Replace("\0", "")); }
/// <summary> /// 过滤script脚本,iframe,frameset /// </summary> /// <param name="str"></param> /// <returns></returns> public static string DeleteScript(string str) { if (str == null) { return(""); } System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); string html = str; html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset return(html); }
public static string ReplaceHtmlTag3(string html) { html = html.Replace("(<style)+[^<>]*>[^\0]*(</style>)+", ""); html = html.Replace(@"\<img[^\>] \>", ""); html = html.Replace(@"<p>", ""); html = html.Replace(@"</p>", ""); System.Text.RegularExpressions.Regex regex0 = new System.Text.RegularExpressions.Regex("(<style)+[^<>]*>[^\0]*(</style>)+", System.Text.RegularExpressions.RegexOptions.Multiline); System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S] </script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S] </iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S] </frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>] \>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex0.Replace(html, ""); //过滤href=javascript: (<A>) 属性 //html = regex10.Replace(html, ""); html = regex3.Replace(html, ""); // _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = regex9.Replace(html, ""); //html = html.Replace(" ", ""); html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); html = html.Replace(" ", ""); html = html.Replace(" ", " "); return(html); }
public static string UrlDonustur(string Yazi) { try { string strSonuc = ToLowerFonksiyonu(Yazi.Trim()); strSonuc = strSonuc.Replace("-", "+"); strSonuc = strSonuc.Replace(" ", "+"); strSonuc = strSonuc.Replace("ç", "c"); strSonuc = strSonuc.Replace("Ç", "C"); strSonuc = strSonuc.Replace("ğ", "g"); strSonuc = strSonuc.Replace("Ğ", "G"); strSonuc = strSonuc.Replace("ı", "i"); strSonuc = strSonuc.Replace("I", "İ"); strSonuc = strSonuc.Replace("ö", "o"); strSonuc = strSonuc.Replace("Ö", "O"); strSonuc = strSonuc.Replace("ş", "s"); strSonuc = strSonuc.Replace("Ş", "S"); strSonuc = strSonuc.Replace("ü", "u"); strSonuc = strSonuc.Replace("Ü", "U"); strSonuc = strSonuc.Trim(); strSonuc = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strSonuc, ""); strSonuc = strSonuc.Trim(); strSonuc = strSonuc.Replace("+", "-"); return(strSonuc); } catch (Exception ex) { throw ex; } }
public static string StripHtml(string Html) { //从Html中录入 <script> 标签<script[^>]*>[sS]*?</script> string scriptregex = @"<script[^>]*>(.*?)</script>"; System.Text.RegularExpressions.Regex scripts = new System.Text.RegularExpressions.Regex(scriptregex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture); string scriptless = scripts.Replace(Html, " "); //从Html中录入 <style> 标签<style[^>]*>(.*?)</style> string styleregex = @"<style[^>]*>(.*?)</style>"; System.Text.RegularExpressions.Regex styles = new System.Text.RegularExpressions.Regex(styleregex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture); string styleless = styles.Replace(scriptless, " "); //从Html中录入 <NOSEARCH> 标签(当 NOSEARCH 在 web.config/Preferences 类中<Preferences 类是项目里面,专门用于获取web.config/app.config>) //TODO: NOTE: this only applies to INDEXING the text - links are parsed before now, so they aren't "excluded" by the region!! (yet) string ignoreless = styleless; //从Html中录入 <!--comment--> 标签 //string commentregex = @"<!--.*?-->"; string commentregex = @"<!(?:--[sS]*?--s*)?>"; System.Text.RegularExpressions.Regex comments = new System.Text.RegularExpressions.Regex(commentregex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture); string commentless = comments.Replace(ignoreless, " "); //从Html中录入 Html 标签 System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex("<(.| )+?>", RegexOptions.IgnoreCase); //替换所有HTML标签以匹配空格字符串 string output = objRegExp.Replace(commentless, " "); //替换所有 < 和 > 为 < 和 > output = output.Replace("<", "<"); output = output.Replace(">", ">"); objRegExp = null; return(ReplaceSpace(output)); }
/// <summary> /// 过滤HTML /// </summary> /// <param name="html"></param> /// <returns></returns> public static string checkStr(string html) { System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); return(html); }
protected override void Render(HtmlTextWriter writer) { var stringWriter = new System.IO.StringWriter(); var htmlWriter = new System.Web.UI.HtmlTextWriter(stringWriter); base.Render(htmlWriter); htmlWriter.Flush(); htmlWriter.Close(); string html = stringWriter.ToString().Replace("\t", " "); html = Regex.Replace(html, "(\r\n){2,}", "\r\n"); html = Regex.Replace(html, "(\r\n\\s+)+(?<Follow>\r\n\\s+</)", "${Follow}"); html = Regex.Replace(html, "\r\n(?<Indent>\\s+)(\r\n\\s+)+", "\r\n${Indent}"); var match = Regex.Match(html, "\r\n(?<Indent>\\s+)<span>Page Events:"); if (match.Success) { string indent = match.Groups["Indent"].Value; html = Regex.Replace(html, "<br />(?<counter><span>[0-9]{12})", "<br />\r\n" + indent + "${counter}"); } Response.Write(html); }
static void Main(string[] args) { string str = "A Thousand Splendid soothing Suns"; Console.WriteLine("Words that start wuth 'S' or 's'..."); ShowMatches(str, @"\b[S|s]\S*"); Console.WriteLine(); str = "make maze and manage to measure it"; Console.WriteLine("Words that start with 'm' and end is 'e'.."); ShowMatches(str, @"\bm\S*e\b"); Console.WriteLine(); str = "hello world nice to meet you again"; string pattern = "\\s+"; string replacement = " "; R.Regex regex = new R.Regex(pattern); string result = regex.Replace(str, replacement); Console.WriteLine("Replacing all extra whitespaces..."); Console.WriteLine(result); }
public static void ExportToCsv_old(string gridViewText, string contentType, HttpResponse response) { const string m_Delimiter_Column = ","; string m_Delimiter_Row = Environment.NewLine; response.ContentType = contentType; System.Text.RegularExpressions.Regex m_RegEx = new System.Text.RegularExpressions.Regex(@"(>\s+<)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); gridViewText = m_RegEx.Replace(gridViewText, "><"); gridViewText = gridViewText.Replace(m_Delimiter_Row, String.Empty); gridViewText = gridViewText.Replace("</td></tr>", m_Delimiter_Row); gridViewText = gridViewText.Replace("<tr><td>", String.Empty); gridViewText = gridViewText.Replace(m_Delimiter_Column, "\\" + m_Delimiter_Column); gridViewText = gridViewText.Replace("</td><td>", m_Delimiter_Column); m_RegEx = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); gridViewText = m_RegEx.Replace(gridViewText, String.Empty); gridViewText = HttpUtility.HtmlDecode(gridViewText); response.Write(gridViewText); response.End(); }
public static string LoadData(string file, NameValueCollection data) { Config cfg = new Config(); if (data == null) { data = new NameValueCollection(); } data["SiteName"] = cfg.GetKey("SiteName"); data["Protocol"] = WebContext.Protocol; data["Server"] = WebContext.ServerName; data["Root"] = WebContext.Root; data["root"] = WebContext.Root; string body = ""; if (file != "") { System.IO.StreamReader s = new System.IO.StreamReader(WebContext.Server.MapPath(file)); body = s.ReadToEnd(); if (data != null) { foreach (string str in data.Keys) { string p = "\\{{1}(?<id>\\w+)\\}{1}"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(p); DictionnaryEvaluator d = new DictionnaryEvaluator(data); body = r.Replace(body, new MatchEvaluator(d.LookUp)); } } s.Close(); } return(body); }
/// <summary> /// HTML转行成TEXT /// </summary> /// <param name="strHtml"></param> /// <returns></returns> public static string HtmlToTxt(string strHtml) { string[] aryReg = { @"<script[^>]*?>.*?</script>", @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+", @"&(quot|#34);", @"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);", @"&(pound|#163);", @"&(copy|#169);", @"&#(\d+);", @"-->", @"<!--.*\n" }; string newReg = aryReg[0]; string strOutput = strHtml; for (int i = 0; i < aryReg.Length; i++) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(aryReg[i], RegexOptions.IgnoreCase); strOutput = regex.Replace(strOutput, string.Empty); } strOutput.Replace("<", ""); strOutput.Replace(">", ""); strOutput.Replace("\r\n", ""); return(strOutput); }
private void textBox2_TextChanged(object sender, EventArgs e) { if (comboBox1.Text != "" && comboBox2.Text != "" && textBox1.Text != "" && textBox2.Text != "") { button1.Enabled = true; } else { button1.Enabled = false; } int curr = this.textBox2.SelectionStart; System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex("[^0-9]+"); this.textBox2.Text = rg.Replace(this.textBox2.Text, ""); if (this.textBox2.SelectionStart == 0) { this.textBox2.SelectionStart = 0; } else { this.textBox2.SelectionStart = curr; } }
private static string AddPathToURLs(Uri path, string fileContent, string hostName) { Regex urls = new System.Text.RegularExpressions.Regex(@"url\s*\([^\)]*\)|src\s*=\s*['|""][^('|"")]+['|""]", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return(urls.Replace(fileContent, delegate(Match match) { string resource = match.ToString().Replace(" ", ""); if (resource.ToLower().Contains(".css")) // do not touch imports /*@import url(bla.css);*/ { return match.ToString(); } if (resource.StartsWith("url(")) /*Eg. background: #EAEAEA url(/RichWidgets/img/Header_Background_Purple.jpg?537) repeat-x top;*/ { resource = resource.Substring(4, resource.Length - 5)/*remove "url(...)*/ .Replace("'", "").Replace("\"", "") /* remove quotes if they exist */; if (resource.ToLower().StartsWith("http") || resource.ToLower().StartsWith("//") ||/*url("//ssl.bla.com/Bar_Gradient.png")*/ resource.ToLower().StartsWith("data:") /*do not touch encoded data url('data:image/png;base64,R0lGODlhDQAE(...)*/) { return "url('" + resource + "')"; } return "url('" + GetAbsolutePathFromRequest(path, resource, hostName) + "')"; } else /*Eg. _filter: progid: DXImageTransform.Microsoft.AlphaImageLoader(src='/RichWidgets/img/Bar_Gradient.png', sizingMethod='scale'); */ { resource = resource.Substring(5, resource.Length - 6); if (resource.ToLower().StartsWith("http") || resource.ToLower().StartsWith("//") ||/*url("//ssl.bla.com/Bar_Gradient.png")*/ resource.ToLower().StartsWith("data:") /*do not touch encoded data url('data:image/png;base64,R0lGODlhDQAE(...)*/) { return "src='" + resource + "'"; } return "src='" + GetAbsolutePathFromRequest(path, resource, hostName) + "'"; } })); }
public string basliktemizlesimdi(string baslik) { baslik = Regex.Replace(baslik, @"\'", string.Empty); baslik = baslik.ToString().ToLower(); if (baslik.Length > 50) { baslik = baslik.Substring(0, 49) + ".."; } baslik = baslik.Replace("'", "-"); string strReturn = baslik.Trim(); strReturn = strReturn.Replace("ğ", "g"); strReturn = strReturn.Replace("Ğ", "g"); strReturn = strReturn.Replace("ü", "u"); strReturn = strReturn.Replace("Ü", "u"); strReturn = strReturn.Replace("ş", "s"); strReturn = strReturn.Replace("Ş", "s"); strReturn = strReturn.Replace("ı", "i"); strReturn = strReturn.Replace("İ", "i"); strReturn = strReturn.Replace("ö", "o"); strReturn = strReturn.Replace("Ö", "o"); strReturn = strReturn.Replace("ç", "c"); strReturn = strReturn.Replace("Ç", "c"); strReturn = strReturn.Replace("-", "+"); strReturn = strReturn.Replace(" ", "+"); strReturn = strReturn.Trim(); strReturn = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strReturn, ""); strReturn = strReturn.Trim(); strReturn = strReturn.Replace("+", "-"); return(strReturn); }
private static void UpdateManifest() { const string path = "Native.MW5.Api.manifest"; const string oldFilename = "name=\"MapWinGIS.ocx\""; const string newFilename = "name=\"MapWinGis\\MapWinGIS.ocx\""; try { var s = File.ReadAllText(path); if (!string.IsNullOrWhiteSpace(s)) { var regex = new System.Text.RegularExpressions.Regex(oldFilename, RegexOptions.IgnoreCase); var newText = regex.Replace(s, newFilename); File.WriteAllText(path, newText); Console.WriteLine("Text was replaced"); } } catch (Exception ex) { Console.WriteLine("Failed to update manifest: " + ex.Message); } }
public static string StripHtml(string Html) { //Stripts the <script> tags from the Html string scriptregex = @"<scr" + @"ipt[^>.]*>[\s\S]*?</sc" + @"ript>"; System.Text.RegularExpressions.Regex scripts = new System.Text.RegularExpressions.Regex(scriptregex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture); string scriptless = scripts.Replace(Html, " "); //Stripts the <style> tags from the Html string styleregex = @"<style[^>.]*>[\s\S]*?</style>"; System.Text.RegularExpressions.Regex styles = new System.Text.RegularExpressions.Regex(styleregex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture); string styleless = styles.Replace(scriptless, " "); //Strips the HTML tags from the Html System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex("<(.|\n)+?>", RegexOptions.IgnoreCase); //Replace all HTML tag matches with the empty string string strOutput = objRegExp.Replace(styleless, " "); // Convert &&amp;eacute; to &eacute; (e') so French words are indexable // ## UNDOCUMENTED ## this line is new in Version 2, but was not documented // in the article... I may explain it when writing about Version 3... ExtendedHtmlUtility ExtHtml = new ExtendedHtmlUtility(); strOutput = ExtHtml.HtmlEntityDecode(strOutput, false); // The above line can be safely commented out on most English pages // since it's unlikely any 'important' characters would be HtmlEncoded //Replace all < and > with < and > strOutput = strOutput.Replace("<", "<"); strOutput = strOutput.Replace(">", ">"); objRegExp = null; return(strOutput); }
/// <summary> /// /// </summary> /// <param name="Html"></param> /// <param name="tagHtmls">If length == 0 is default tags</param> /// <returns></returns> public static string StripHtml(string Html, string[] tagHtmls) { //Stripts the <tagHtml> tags from the Html string tagBegin = ""; string tagEnd = ""; string strBegin = ""; if (tagHtmls.Length == 0) { tagHtmls = new string[] { "input", "form", "script", "div", "table", "p", "hr", "ul", "li", "img", "table", "tbody", "tr", "td", "th" }; } System.Text.RegularExpressions.Regex tagStripEnd; foreach (string tagHtml in tagHtmls) { tagBegin = @"<" + tagHtml + @"[\s\S]*?>"; System.Text.RegularExpressions.Regex tagStripBegin = new System.Text.RegularExpressions.Regex(tagBegin, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture); strBegin = tagStripBegin.Replace(Html, string.Empty); tagEnd = @"</" + tagHtml + ">"; tagStripEnd = new System.Text.RegularExpressions.Regex(tagEnd, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture); Html = tagStripEnd.Replace(strBegin, string.Empty); } return(Html); }
/// <summary> /// 从HTML中获取文本,保留br,p,img /// </summary> /// <param name="HTML"></param> /// <returns></returns> public static string GetTextFromHTML(string HTML) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return(regEx.Replace(HTML, "")); }
public static string GetCleanName(string name) { return(Regex.Replace(name, @"[\W_]+", "_").ToLower()); }
protected string RemoveHTMLTag(string HTML) { // Xóa các thẻ html System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex("<[^>]*>"); return(objRegEx.Replace(HTML, "")); }
private void btnAdd_Click(object sender, System.EventArgs e) { int displaySequence; decimal salePrice; decimal?costPrice; decimal?marketPrice; int stock; int factstock; decimal?num4; decimal?referralDeduct; decimal?subMemberDeduct; decimal?subReferralDeduct; decimal?deductFee; int buyCardinality; decimal?grossweight; //销售类型 int saletype = string.IsNullOrWhiteSpace(this.dropSaleType.SelectedValue) ? 1 : Convert.ToInt32(this.dropSaleType.SelectedValue); if (!this.ValidateConverts(this.chkSkuEnabled.Checked, out displaySequence, out salePrice, out costPrice, out marketPrice, out stock, out factstock, out num4, out referralDeduct, out subMemberDeduct, out subReferralDeduct, out deductFee, out buyCardinality, out grossweight)) { return; } if (saletype != 2) { if (this.ddlImportSourceType.SelectedValue == null || this.ddlImportSourceType.SelectedValue == 0) { this.ShowMsg("请选择原产地", false); return; } } if (saletype != 2) { if (this.ddlSupplier.SelectedValue == null || this.ddlSupplier.SelectedValue == 0) { this.ShowMsg("请选择供货商", false); return; } } if (this.ddlUnit.SelectedValue == null || this.ddlUnit.SelectedValue == "") { this.ShowMsg("请选择计量单位", false); return; } if (this.ddlShipping.SelectedValue == null || this.ddlShipping.SelectedValue == 0) { this.ShowMsg("请选择运费模版", false); return; } int ConversionRelation; if (!int.TryParse(this.txtConversionRelation.Text, out ConversionRelation)) { this.ShowMsg("输入换算关系不正确", false); return; } if (!this.chkSkuEnabled.Checked) { if (salePrice <= 0m) { this.ShowMsg("商品一口价必须大于0", false); return; } if (costPrice.HasValue && (costPrice.Value > salePrice || costPrice.Value < 0m)) { this.ShowMsg("商品成本价必须大于0且小于商品一口价", false); return; } if (!costPrice.HasValue) //|| !deductFee.HasValue { this.ShowMsg("商品成本价不能为空", false); //与扣点 return; } if (string.IsNullOrEmpty(txtProductStandard.Text)) { this.ShowMsg("未开启多规格时,商品规格必填", false); return; } } string text = Globals.StripScriptTags(this.txtProductName.Text.Trim()); text = Globals.StripHtmlXmlTags(text).Replace("\\", "").Replace("'", ""); if (string.IsNullOrEmpty(text) || text == "") { this.ShowMsg("商品名称不能为空,且不能包含脚本标签、HTML标签、XML标签、反斜杠(\\)、单引号(')!", false); return; } //判断是否存在广告关键字 Dictionary <string, string> msg; if (!ValidateKeyWordHelper.ValidateKeyWord(new Dictionary <string, string>() { { "商品名称", this.txtProductName.Text }, { "商品简介", this.txtShortDescription.Text } }, out msg)) { System.Text.StringBuilder showMsg = new System.Text.StringBuilder(); foreach (string k in msg.Keys) { showMsg.Append(k + "中不能包含广告词:" + msg[k] + ";"); } this.ShowMsg(showMsg.ToString(), false); return; } string text2 = this.editDescription.Text; string text3 = this.editmobbileDescription.Text; if (this.ckbIsDownPic.Checked) { text2 = base.DownRemotePic(text2); text3 = base.DownRemotePic(text3); } System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<script[^>]*?>.*?</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); ProductInfo productInfo = new ProductInfo { CategoryId = this.categoryId, TypeId = this.dropProductTypes.SelectedValue, ProductName = text, EnglishName = this.txtEnglishName.Text, SysProductName = this.txtsysProductName.Text.Trim(), ProductCode = this.txtProductCode.Text, MarketPrice = marketPrice, Unit = this.ddlUnit.SelectedItem.Text, ImageUrl1 = this.uploader1.UploadedImageUrl, ImageUrl2 = this.uploader2.UploadedImageUrl, ImageUrl3 = this.uploader3.UploadedImageUrl, ImageUrl4 = this.uploader4.UploadedImageUrl, ImageUrl5 = this.uploader5.UploadedImageUrl, ThumbnailUrl40 = this.uploader1.ThumbnailUrl40, ThumbnailUrl60 = this.uploader1.ThumbnailUrl60, ThumbnailUrl100 = this.uploader1.ThumbnailUrl100, ThumbnailUrl160 = this.uploader1.ThumbnailUrl160, ThumbnailUrl180 = this.uploader1.ThumbnailUrl180, ThumbnailUrl220 = this.uploader1.ThumbnailUrl220, ThumbnailUrl310 = this.uploader1.ThumbnailUrl310, ThumbnailUrl410 = this.uploader1.ThumbnailUrl410, ShortDescription = this.txtShortDescription.Text, IsCustomsClearance = this.ChkisCustomsClearance.Checked, Description = (!string.IsNullOrEmpty(text2) && text2.Length > 0) ? regex.Replace(text2, "") : null, MobblieDescription = (!string.IsNullOrEmpty(text3) && text3.Length > 0) ? regex.Replace(text3, "") : null, Title = this.txtTitle.Text, MetaDescription = this.txtMetaDescription.Text, MetaKeywords = this.txtMetaKeywords.Text, AddedDate = System.DateTime.Now, BrandId = this.dropBrandCategories.SelectedValue, MainCategoryPath = CatalogHelper.GetCategory(this.categoryId).Path + "|", IsfreeShipping = this.ChkisfreeShipping.Checked, ReferralDeduct = referralDeduct, SubMemberDeduct = subMemberDeduct, SubReferralDeduct = subReferralDeduct, TaxRateId = this.dropTaxRate.SelectedValue, TemplateId = this.ddlShipping.SelectedValue, SupplierId = this.ddlSupplier.SelectedValue, ImportSourceId = this.ddlImportSourceType.SelectedValue, IsApproved = true, BuyCardinality = buyCardinality, UnitCode = this.ddlUnit.SelectedValue, Manufacturer = txtManufacturer.Text, ItemNo = txtItemNo.Text, BarCode = txtBarCode.Text, Ingredient = txtIngredient.Text, ProductStandard = txtProductStandard.Text, ConversionRelation = ConversionRelation, ProductTitle = this.txtProductTitle.Text, SaleType = saletype, IsPromotion = this.ChkisPromotion.Checked, IsDisplayDiscount = this.ChkisDisplayDiscount.Checked, Purchase = int.Parse(this.Rd_Purchase.SelectedValue), SectionDay = int.Parse(this.txtSectionDay.Text), PurchaseMaxNum = int.Parse(this.txtMaxCount.Text.ToString()) }; ProductSaleStatus saleStatus = ProductSaleStatus.OnSale; if (this.radInStock.Checked) { saleStatus = ProductSaleStatus.OnStock; } if (this.radUnSales.Checked) { saleStatus = ProductSaleStatus.UnSale; } if (this.radOnSales.Checked) { saleStatus = ProductSaleStatus.OnSale; if (productInfo.SaleType != 2) { this.ShowMsg("商品还未完成归类操作,不能出售", false); return; } } productInfo.SaleStatus = saleStatus; //如果是组合商品,默认已审价 if (productInfo.SaleType == 2) { productInfo.IsApprovedPrice = 1; } else { productInfo.IsApprovedPrice = 0; } System.Collections.Generic.Dictionary <int, System.Collections.Generic.IList <int> > attrs = null; System.Collections.Generic.Dictionary <string, SKUItem> dictionary; if (this.chkSkuEnabled.Checked) { productInfo.HasSKU = true; dictionary = base.GetSkus(this.txtSkus.Text); } else { AutoCalcCostPriceAndDeductFee(salePrice, ref costPrice, ref deductFee); dictionary = new System.Collections.Generic.Dictionary <string, SKUItem> { { "0", new SKUItem { SkuId = "0", SKU = Globals.HtmlEncode(Globals.StripScriptTags(this.txtSku.Text.Trim()).Replace("\\", "")), SalePrice = salePrice, CostPrice = costPrice.HasValue ? costPrice.Value : 0m, Stock = stock, FactStock = factstock, Weight = num4.HasValue ? num4.Value : 0m, DeductFee = deductFee.HasValue ? deductFee.Value :0m, GrossWeight = grossweight.HasValue?grossweight.Value:0m } } }; if (this.txtMemberPrices.Text.Length > 0) { base.GetMemberPrices(dictionary["0"], this.txtMemberPrices.Text); } } if (!string.IsNullOrEmpty(this.txtAttributes.Text) && this.txtAttributes.Text.Length > 0) { attrs = base.GetAttributes(this.txtAttributes.Text); } ValidationResults validationResults = Validation.Validate <ProductInfo>(productInfo, new string[] { "AddProduct" }); if (!validationResults.IsValid) { this.ShowMsg(validationResults); return; } System.Collections.Generic.IList <int> list = new System.Collections.Generic.List <int>(); if (!string.IsNullOrEmpty(this.txtProductTag.Text.Trim())) { string text4 = this.txtProductTag.Text.Trim(); string[] array; if (text4.Contains(",")) { array = text4.Split(new char[] { ',' }); } else { array = new string[] { text4 }; } string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string value = array2[i]; list.Add(System.Convert.ToInt32(value)); } } #region ==组合商品 List <ProductsCombination> combinations = new List <ProductsCombination>(); string combinationInfos = base.Request.Form["selectProductsinfo"]; string[] curCom = combinationInfos.Split(new char[] { ',' }); string[] curCom2 = curCom; for (int i = 0; i < curCom2.Length; i++) { string combinationInfo = curCom2[i]; ProductsCombination com = new ProductsCombination(); string[] array3 = combinationInfo.Split(new char[] { '|' }); if (array3.Length == 10) { com.SkuId = array3[0]; com.ProductId = array3[1] == "" ? 0 : Convert.ToInt32(array3[1]); com.ProductName = array3[2]; com.ThumbnailsUrl = array3[3]; decimal tempweight; if (decimal.TryParse(array3[4], out tempweight)) { com.Weight = tempweight; } com.SKU = array3[5]; com.SKUContent = array3[6]; com.Quantity = array3[8] == "" ? 0 : Convert.ToInt32(array3[8]); decimal tempprice; if (decimal.TryParse(array3[9], out tempprice)) { com.Price = tempprice; } combinations.Add(com); } } productInfo.CombinationItemInfos = combinations; #endregion if (productInfo.SaleType == 2) { decimal CombinationTotalPrice = 0M; foreach (var item in productInfo.CombinationItemInfos) { CombinationTotalPrice += item.Price * item.Quantity; } if (Math.Round(CombinationTotalPrice, 2) != Math.Round(salePrice, 2)) { this.ShowMsg("添加商品失败,组合商品一口价和组合商品明细总价不一致", false); return; } } ProductActionStatus productActionStatus = ProductHelper.AddProduct(productInfo, dictionary, attrs, list, combinations); if (productActionStatus == ProductActionStatus.Success) { this.ShowMsg("添加商品成功", true); base.Response.Redirect(Globals.GetAdminAbsolutePath(string.Format("/product/AddProductComplete.aspx?categoryId={0}&productId={1}", this.categoryId, productInfo.ProductId)), true); return; } if (productActionStatus == ProductActionStatus.AttributeError) { this.ShowMsg("添加商品失败,保存商品属性时出错", false); return; } if (productActionStatus == ProductActionStatus.DuplicateName) { this.ShowMsg("添加商品失败,商品名称不能重复", false); return; } if (productActionStatus == ProductActionStatus.DuplicateSKU) { this.ShowMsg("添加商品失败,商家编码不能重复", false); return; } if (productActionStatus == ProductActionStatus.SKUError) { this.ShowMsg("添加商品失败,商品规格错误", false); return; } if (productActionStatus == ProductActionStatus.ProductTagEroor) { this.ShowMsg("添加商品失败,保存商品标签时出错", false); return; } this.ShowMsg("添加商品失败,未知错误", false); }
public string Replace(string inputString, string replacement) { return(_regex.Replace(inputString, replacement)); }