C# (CSharp) System.Text.RegularExpressions Regex.Replace Beispiele

C# (CSharp) System.Text.RegularExpressions Regex.Replace - 30 Beispiele gefunden. Dies sind die am besten bewerteten C# (CSharp) Beispiele für die System.Text.RegularExpressions.Regex.Replace, die aus Open Source-Projekten extrahiert wurden. Sie können Beispiele bewerten, um die Qualität der Beispiele zu verbessern.

Replace() public method

public Replace ( string input, System evaluator ) : string
input string
evaluator System
return string
Beispiel #1
0
 //+ボタンが押されたときに追加
 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);
     }
 }
Beispiel #2
0
        /// <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);
        }
Beispiel #3
0
        /// <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;
        }
Beispiel #4
0
        /// <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;
        }
Beispiel #5
0
        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);
        }
Beispiel #6
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;
 }
Beispiel #7
0
		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
				);
			}
		}
        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);
        }
        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();
        }
Beispiel #10
0
        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);
                    }
                }
            }
        }
Beispiel #11
0
        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;
        }
Beispiel #12
0
        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;
        }
        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);
        }
Beispiel #14
0
 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 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);
        }
        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;
        }
Beispiel #17
0
 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();
 }
Beispiel #18
0
 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;
     }
 }
Beispiel #19
0
        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;
            }
        }
Beispiel #20
0
        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));
        }
Beispiel #23
0
 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);
 }
        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");
            }
        }
Beispiel #25
0
        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));
        }
Beispiel #26
0
	/// <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);
        }
 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);
 }
Beispiel #29
0
        // 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");
            }
        }