System.Text.RegularExpressions.Regex.Replace(string, string)

Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Replace(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1115 Examples 7

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineCollectionFormatterType(Type type, Type elementType)
        {
            VerifyTypeIsPublic(type);

            string pre = "Array2.";
            if (Array1FormatterHelper.IsArray1Type(elementType))
            {
                pre = "Array1.";
            }

            Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
            TypeBuilder typeBuilder = DefineType("Bssom.Formatters." + pre + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.NotPublic | TypeAttributes.Sealed, null, new[] { formatterType });
            return typeBuilder;
        }

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineFormatterType(Type type)
        {
            VerifyTypeIsPublic(type);

            Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
            TypeBuilder typeBuilder = DefineType("Bssom.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.NotPublic | TypeAttributes.Sealed, null, new[] { formatterType });
            return typeBuilder;
        }

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineFormatterDelegateType(Type type)
        {
            TypeBuilder typeBuilder = DefineType("Bssom.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "FormatterDelegate" + Interlocked.Increment(ref nameSequence), TypeAttributes.NotPublic | TypeAttributes.Sealed, null, null);
            return typeBuilder;
        }

19 View Source File : DynamicAssembly.cs
License : MIT License
Project Creator : 1996v

public TypeBuilder DefineInterfaceImpType(Type interfaceType)
        {
            VerifyTypeIsPublic(interfaceType);

            TypeBuilder typeBuilder = DefineType("Bssom.DynamicInterfaceImp." + SubtractFullNameRegex.Replace(interfaceType.FullName, string.Empty).Replace(".", "_") + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { interfaceType });
            return typeBuilder;
        }

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

19 View Source File : UnityARBuildPostprocessor.cs
License : MIT License
Project Creator : 734843327

internal static bool ReplaceCppMacro(string[] lines, string name, string newValue)
	{
		bool replaced = false;
		Regex matchRegex = new Regex(@"^.*#\s*define\s+" + name);
		Regex replaceRegex = new Regex(@"^.*#\s*define\s+" + name + @"(:?|\s|\s.*[^\\])$");
		for (int i = 0; i < lines.Count(); i++)
		{
			if (matchRegex.Match (lines [i]).Success) {
				lines [i] = replaceRegex.Replace (lines [i], "#define " + name + " " + newValue);
				replaced = true;
			}
		}
		return replaced;
	}

19 View Source File : NumberParse.cs
License : MIT License
Project Creator : abock

static (string str, int @base, bool negate) Configure(string str)
        {
            str = str.Trim();

            var negate = false;
            if (str.Length > 0 && str[0] == '-')
            {
                negate = true;
                str = str.Substring(1);
            }

            str = strip.Replace(str, string.Empty);

            int @base = 10;

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(2);
            }
            else if (str.EndsWith("h", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(0, str.Length - 1);
            }
            else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
            {
                @base = 2;
                str = str.Substring(2);
            }

            return (str, @base, negate);
        }

19 View Source File : Example.cs
License : MIT License
Project Creator : ABTSoftware

private string ParseHtmlDescription(string description)
        {
            if (string.IsNullOrEmpty(description)) return string.Empty;

            var formatted = description
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", "<br/>")
                .Replace("[b][i]", "<strong><em>")
                .Replace("[i][b]", "<strong><em>")
                .Replace("[b]", "<strong>")
                .Replace("[i]", "<em>")
                .Replace("[/b][/i]", "</em></strong>")
                .Replace("[/i][/b]", "</em></strong>")
                .Replace("[/b]", "</strong>")
                .Replace("[/i]", "</em>");

            const string replace = "<a href=\"$1\" target=\"_blank\">$2</a>";

            formatted = _urlRegex.Replace(formatted, replace);

            return formatted;
        }

19 View Source File : Example.cs
License : MIT License
Project Creator : ABTSoftware

private string ParseFormattedDescription(string formattedDescription)
        {
            if (string.IsNullOrEmpty(formattedDescription)) return string.Empty;

            var formatted = formattedDescription
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", "<LineBreak/>")
                .Replace("[b][i]", "<Run FontWeight=\"Bold\" FontStyle=\"Italic\">")
                .Replace("[i][b]", "<Run FontWeight=\"Bold\" FontStyle=\"Italic\">")
                .Replace("[b]", "<Run FontWeight=\"Bold\">")
                .Replace("[i]", "<Run FontStyle=\"Italic\">")
                .Replace("[/b][/i]", "</Run>")
                .Replace("[/i][/b]", "</Run>")
                .Replace("[/b]", "</Run>")
                .Replace("[/i]", "</Run>");

#if SILVERLIGHT
            const string replace = "<Hyperlink Foreground=\"{StaticResource SciChartGreenBrush}\" " +
                                            "MouseOverForeground=\"{StaticResource SciChartDarkGreenBrush}\" " + 
                                            "TextDecorations=\"Underline\" " + 
                                            "MouseOverTextDecorations=\"None\" " + 
                                            "NavigateUri=\"$1\" TargetName=\"_blank\">" + 
                                                "<Run>$2</Run>" + 
                                   "</Hyperlink>";
#else 
            const string replace = "<Hyperlink Style=\"{DynamicResource HyperlinkStyle}\" NavigateUri=\"$1\"><Run>$2</Run></Hyperlink>";
#endif

            // TO dump all links out to console, uncomment 
            // 

//            Regex urlRegexShort = new Regex(@"\[url='(.*?)'?\]");
//            var allLinks = urlRegexShort.Matches(formatted)
//                .Cast<Match>()
//                .Select(x => x.ToString().Replace("url=[", "").Replace("]", ""))
//                .Distinct()
//                .Select(y => string.Format("{0}\t{1}", this.replacedle, y))
//                .OrderBy(x => x)
//                .ToList();
//
//            foreach (var match in allLinks)
//            {
//                Trace.WriteLine(match);
//            }
                

            formatted = _urlRegex.Replace(formatted, replace);

            return formatted;
        }

19 View Source File : Example.cs
License : MIT License
Project Creator : ABTSoftware

private string SimplifyDescription(string formattedDescription)
        {
            if (string.IsNullOrEmpty(formattedDescription)) return string.Empty;

            var formatted = formattedDescription
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", " ")
                .Replace("    ", " ")
                .Replace("   ", " ")
                .Replace("  ", " ")
                .Replace("[b]", string.Empty)
                .Replace("[/b]", string.Empty)
                .Replace("[i]", string.Empty)
                .Replace("[i]", string.Empty)
                .Trim();

            formatted = _urlRegex.Replace(formatted, "$2");

            return formatted;
        }

19 View Source File : CreateInvertedIndex.cs
License : MIT License
Project Creator : ABTSoftware

public static IList<string> GetTerms(string text)
        {
            text = text.ToLower();
            text = new Regex(@"\W").Replace(text, " ");

            var words = text.Split(' ').Where(x => x != "").Where(word => !_stopWords.Contains(word)).ToArray();

            var tokenizer = new NGramTokenizer();
            var terms = words
                .Select(tokenizer.Tokenize)
                .SelectMany(strings => strings.SelectMany(inner => inner))
                .Select(sb => sb.ToString())
                .Where(s => !string.IsNullOrEmpty(s) && s.Length > 1)
                .ToList();

            return terms;
        }

19 View Source File : ExampleSearchProvider.cs
License : MIT License
Project Creator : ABTSoftware

public IEnumerable<ExampleId> Query(string text)
        {
            text = text.ToLower();
            text = new Regex(@"\W").Replace(text, " ");

            var terms = text.Split(' ').ToArray();

            IEnumerable<ExampleId> result = null;
            if (terms.Length > 1)
            {
                result = FreeTextQuery(terms);
            }
            else if (terms.Length == 1)
            {
                result = OneWordQuery(terms);
            }

            return result;
        }

19 View Source File : IOExtensions.cs
License : MIT License
Project Creator : Accelerider

public static string GetUniqueLocalPath(this string @this, Func<string, bool> predicate = null)
        {
            if (predicate == null) predicate = File.Exists;

            var directoryName = Path.GetDirectoryName(@this) ?? throw new InvalidOperationException();
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(@this) ?? throw new InvalidOperationException();
            fileNameWithoutExtension = FileNameCountRegex.Replace(fileNameWithoutExtension, string.Empty).Trim();
            var extension = Path.GetExtension(@this);
            for (int i = 2; predicate(@this); i++)
            {
                @this = $"{Path.Combine(directoryName, fileNameWithoutExtension)} ({i}){extension}";
            }

            return @this;
        }

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : adamant

public static string NormalizeLineEndings(this string input, string lineEnding)
        {
            return LineEndings.Replace(input, lineEnding);
        }

19 View Source File : WebAppSettings.cs
License : MIT License
Project Creator : Adoxio

private static string GetInstanceId()
		{
			var id = GetAppSettingOrEnvironmentVariable("WEBSITE_INSTANCE_ID")
				?? HostingEnvironment.ApplicationID;

			if (!string.IsNullOrWhiteSpace(id))
			{
				var permitted = new Regex("[^0-9a-zA-Z_.-]");
				return permitted.Replace(id, ".");
			}

			return null;
		}

19 View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private IAnnotationFile GetAnnotationFile(Enreplacedy note, Guid id)
		{
			var isDoreplacedent = note.GetAttributeValue<bool>("isdoreplacedent");
			if (!isDoreplacedent) return null;

			var fileName = note.GetAttributeValue<string>("filename");

			var storageAccount = GetStorageAccount(_dependencies.GetServiceContext());
			var regex = new Regex(@"\.azure\.txt$");
			var azure = regex.IsMatch(fileName);

			var file = azure ? new AzureAnnotationFile() as IAnnotationFile : new CrmAnnotationFile();

			file.SetAnnotation(() => GetAnnotationWithDoreplacedent(id));

			if (azure)
			{
				var blobFileName = regex.Replace(fileName, string.Empty);
				var blobFile = file as AzureAnnotationFile;
				if (storageAccount != null)
				{
					blobFile.BlockBlob = GetBlockBlob(storageAccount, id, blobFileName);
					if (blobFile.BlockBlob.Exists())
					{
						blobFile.FileName = blobFileName;
						blobFile.FileSize = new FileSize(blobFile.BlockBlob == null ? 0 : Convert.ToUInt64(blobFile.BlockBlob.Properties.Length));
						blobFile.MimeType = blobFile.BlockBlob.Properties.ContentType;
					}
				}
			}
			else
			{
				var crmFile = file as CrmAnnotationFile;
				crmFile.FileName = fileName;
				var size = note.GetAttributeValue<int>("filesize");
				crmFile.FileSize = new FileSize(size > 0 ? Convert.ToUInt64(size) : 0);
				crmFile.MimeType = note.GetAttributeValue<string>("mimetype");
				crmFile.SetDoreplacedent(() => GetFileDoreplacedent(file));
			}


			return file;
		}

19 View Source File : ContentFieldBuilder.cs
License : MIT License
Project Creator : Adoxio

private static string NormalizeWhitespace(string content)
		{
			return WhitespaceNormalizationPattern.Replace(content, " ").Trim();
		}

19 View Source File : ContentFieldBuilder.cs
License : MIT License
Project Creator : Adoxio

private static string StripHtml(string content)
		{
			return HtmlElementPattern.Replace(content, string.Empty);
		}

19 View Source File : ContentFieldBuilder.cs
License : MIT License
Project Creator : Adoxio

private static string StripLiquid(string content)
		{
			return LiquidTagPattern.Replace(content, string.Empty);
		}

19 View Source File : LiquidExtensions.cs
License : MIT License
Project Creator : Adoxio

public string GetMemberName(string name)
			{				
				return _regex2.Replace(_regex1.Replace(name, "$1_$2"), "$1_$2").ToLowerInvariant();
			}

19 View Source File : NumberFormatFilters.cs
License : MIT License
Project Creator : Adoxio

public static string MaxDecimals(object number, int decimals, string culture = "")
		{
			var result = Decimals(number, decimals, culture);
			if (new Regex(string.Format("\\{0}", CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator)).IsMatch(result))
			{
				var zeroRegex = new Regex("0+$");
				var decimalRegex = new Regex(string.Format("\\{0}$", CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator));
				result = zeroRegex.Replace(result, string.Empty);
				result = decimalRegex.Replace(result, string.Empty);
			}
			return result;
		}

19 View Source File : ArgumentDictionary.cs
License : MIT License
Project Creator : Adoxio

public void AddRange(params string[] args)
		{
			string parameter = null;

			foreach (string arg in args)
			{
				string[] parts = _splitter.Split(arg, 3);

				switch (parts.Length)
				{
					case 1:
						// this is a value for the previous parameter
						if (parameter != null)
						{
							parts[0] = _remover.Replace(parts[0], "$1");
							this[parameter] = parts[0];
							parameter = null;
						}
						break;
					case 2:
						// found an argument without a value or with a pending value
						if (parameter != null)
						{
							this[parameter] = "true";
						}

						parameter = parts[1];
						break;
					case 3:
						// found an argument with key and value
						if (parameter != null)
						{
							this[parameter] = "true";
						}

						parameter = parts[1];
						parts[2] = _remover.Replace(parts[2], "$1");
						this[parameter] = parts[2];
						parameter = null;
						break;
				}
			}

			if (parameter != null)
			{
				this[parameter] = "true";
			}
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private static string GetFormattedDescription(string description)
		{
			if (string.IsNullOrWhiteSpace(description))
			{
				return string.Empty;
			}

			var numbering = new Regex(@"(?= \d?\d\) )");

			return numbering.Replace(description, "\n\n");
		}

19 View Source File : DialoguePatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void FixString(NPC speaker, ref string input)
        {

            //Monitor.Log($"checking string: {input}");

            Regex pattern1 = new Regex(prefix + @"(?<key>[^\^]+)", RegexOptions.Compiled);

            while (pattern1.IsMatch(input))
            {
                var match = pattern1.Match(input);
                Dictionary<string, string> dialogueDic = null;
                try
                {
                    dialogueDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{speaker.Name}", ContentSource.GameContent);
                }
                catch
                {
                }

                string key = match.Groups["key"].Value;

                if (dialogueDic != null && dialogueDic.ContainsKey(key))
                {
                    Regex pattern2 = new Regex(prefix + key + @"\^.*\^" + suffix + key, RegexOptions.Compiled);
                    Monitor.Log($"{speaker.Name} has dialogue for {key}", LogLevel.Debug);
                    input = pattern2.Replace(input, dialogueDic[key]);
                }
                else
                {
                    //Monitor.Log($"edited input: {input}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^","");
                    Monitor.Log($"reverted input: {input}");
                }
            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void MakeListString(string a, ref string line, float scale)
        {
            a = new Regex(@"\.[^.]+$").Replace(a, "");
            string[] aa = a.Split('_');
            for(int i = 0; i < aa.Length; i++)
            {
                line = line.Replace("{"+ (i + 1) + "}", aa[i]);
            }
            float width = api.GetScreenSize().X - Config.MarginX * 2;
            int j = 0;
            string ow = line;
            while (Game1.dialogueFont.MeasureString(line).X * scale > width)
            {
                line = line.Substring(0, ow.Length - 3 - j++) + "...";
            }
        }

19 View Source File : DialoguePatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void FixString(NPC speaker, ref string input)
        {

           Monitor.Log($"checking string: {input}");

            Regex pattern1 = new Regex(prefix + @"(?<key>[^\^]+)", RegexOptions.Compiled);

            while (pattern1.IsMatch(input))
            {
                string oldput = input;
                var match = pattern1.Match(input);
                string key = match.Groups["key"].Value;
                Dictionary<string, string> dialogueDic = null;
                try
                {
                    dialogueDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{speaker.Name}", ContentSource.GameContent);
                }
                catch(Exception ex)
                {
                    Monitor.Log($"Error loading character dictionary for {speaker.Name}:\r\n{ex}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^", "");
                    Monitor.Log($"reverted input: {input}");
                }


                if (dialogueDic != null && dialogueDic.ContainsKey(key))
                {
                    Regex pattern2 = new Regex(prefix + key + @"\^.*\^" + suffix + key, RegexOptions.Compiled);
                    Monitor.Log($"{speaker.Name} has dialogue for {key}", LogLevel.Debug);
                    input = pattern2.Replace(input, dialogueDic[key]);
                }
                else
                {
                    //Monitor.Log($"edited input: {input}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^", "");
                    Monitor.Log($"reverted input: {input}");
                }
                Monitor.Log($"edited string: {input}");
                if (input == oldput)
                {
                    Monitor.Log($"Error editing input, aborting.", LogLevel.Error);
                    return;
                }
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

internal static void MakeZombieSpeak(ref string dialogue, bool dontAngry = false)
        {
            monitor.Log($"input {dialogue}");

            string[] strs = dialogue.Split('#');
            for(int i = 0; i < strs.Length; i++)
            {
                string str = strs[i];
                if (str.StartsWith("$") || str.StartsWith("%") || str.StartsWith("[") || str.Length == 0)
                    continue;
                if (i > 0 && strs[i - 1].StartsWith("$r ") && !ModEntry.playerZombies.ContainsKey(Game1.player.uniqueMultiplayerID))
                    continue;

                Regex x1 = new Regex(@"\$[hsuln]");
                Regex x2 = new Regex(@"\$neutral");
                Regex x3 = new Regex(@"\$[0-9]+");

                Regex r1 = new Regex(@"[AEIOU]");
                Regex r1a = new Regex(@"[aeiou]");
                Regex r2 = new Regex(@"[RSTLNDCM]");
                Regex r2a = new Regex(@"[rstlndcm]");
                Regex r3 = new Regex(@"[GH]");
                Regex r3a = new Regex(@"[gh]");
                Regex r4 = new Regex(@"[BFJKPQVWXYZ]");
                Regex r4a = new Regex(@"[bfjkpqvwxyz]");

                str = x1.Replace(str, "");
                str = x2.Replace(str, "");
                str = x3.Replace(str, "");

                str = r1.Replace(str, "A");
                str = r2.Replace(str, "R");
                str = r3.Replace(str, "GH");
                str = r4.Replace(str, "A");

                str = r1a.Replace(str, "a");
                str = r2a.Replace(str, "r");
                str = r3a.Replace(str, "gh");
                str = r4a.Replace(str, "a");

                if(!dontAngry && (i == 0 || !strs[i - 1].StartsWith("$r ")))
                    str += "$a";
                strs[i] = str;
            }

            dialogue = string.Join("#", strs);

            monitor.Log($"zombified: {dialogue}");

        }

19 View Source File : AnarchyExtensions.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static string RemoveHex(this string str) =>
            hexCode.Replace(str, string.Empty).Replace("[-]", string.Empty);

19 View Source File : AnarchyExtensions.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static string ToHTMLFormat(this string str)
        {
            if (hexCode.IsMatch(str))
            {
                str = str.Contains("[-]")
                    ? hexCode.Replace(str, "<color=#$1>").Replace("[-]", "</color>")
                    : hexCode.Replace(str, "<color=#$1>");
                var c = (short)(str.CountWords("<color=") - str.CountWords("</color>"));
                for (short i = 0; i < c; i++)
                {
                    str += "</color>";
                }
            }

            return str;
        }

19 View Source File : HtmlHack.cs
License : MIT License
Project Creator : Aeroblast

public static string Hack(string html)
        {
            int random = Util.RandomRange();
            
            html = regScript.Replace(html, "");
            html = regLink.Replace(html, "$1?r=" + random + "$2");
            //html = regHref.Replace(html, "$1 onclick=\"Href(this);event.stopPropagation();return false;\"$2");
            cssInject = string.Format(cssInject, random);
            jsInject = string.Format(jsInject, random);
            html = html.Replace("</head>", cssInject + "\n</head>").Replace("</body>", jsInject + "\n</body>");
            return html;
        }

19 View Source File : CreditCardNumberValidator.cs
License : MIT License
Project Creator : afucher

public bool Validate(string value)
        {
            // Remove spaces and dashes
            var cleanCreditCardNumber = new Regex(@"[\s-]+")
                .Replace(value, "");

            // Is all digits with length between 8 and 19?
            var isValidNumberFormat = new Regex(@"^[0-9]{8,19}$")
                .Match(cleanCreditCardNumber).Success;

            if (isValidNumberFormat) return IsValidLuhnAlgorithm(cleanCreditCardNumber);
           
            return false;

            
        }

19 View Source File : PropertyInvocationAnalyzerBase.cs
License : Apache License 2.0
Project Creator : agoda-com

private void replacedyzeIdentifier(SyntaxNodereplacedysisContext context)
        {
            var identifierSyntax = (IdentifierNameSyntax) context.Node;
            var memberAccess = identifierSyntax?.Identifier.Parent?.Parent as MemberAccessExpressionSyntax;
            if (memberAccess == null) return;

            var memberType = context.SemanticModel.GetTypeInfo(memberAccess.Expression);
            if (!(memberType.Type is INamedTypeSymbol namedTypeSymbol))
            {
                return;
            }

            var constructedFrom = namedTypeSymbol.ConstructedFrom.ToDisplayString();
            // if it's a generic type then ignore the generic component
            constructedFrom = MatchGeneric.Replace(constructedFrom, "");

            if (Rules.Any(rule => !rule.Verify(constructedFrom, identifierSyntax.Identifier.Text)))
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation()));
            }
        }

19 View Source File : ServiceLocation.cs
License : MIT License
Project Creator : AiursoftWeb

private async Task<IDnsQueryResponse> QueryDNS(string host)
        {
            var httpsRegex = new Regex("^https://", RegexOptions.Compiled);
            var httpRegex = new Regex("^http://", RegexOptions.Compiled);
            host = httpsRegex.Replace(host, string.Empty);
            host = httpRegex.Replace(host, string.Empty);
            var lookup = new LookupClient();
            var result = await lookup.QueryAsync(host, QueryType.ANY);
            return result;
        }

19 View Source File : ProcessManager.cs
License : MIT License
Project Creator : Akaion

private List<Module> GetModules()
        {
            var modules = new List<Module>();

            if (IsWow64)
            {
                var filePathRegex = new Regex("System32", RegexOptions.IgnoreCase);

                foreach (var entry in ReadWow64PebEntries().Values)
                {
                    // Read the file path of the entry

                    var entryFilePathBytes = Memory.ReadBlock((IntPtr) entry.FullDllName.Buffer, entry.FullDllName.Length);

                    var entryFilePath = filePathRegex.Replace(Encoding.Unicode.GetString(entryFilePathBytes), "SysWOW64");

                    // Read the name of the entry

                    var entryNameBytes = Memory.ReadBlock((IntPtr) entry.BaseDllName.Buffer, entry.BaseDllName.Length);

                    var entryName = Encoding.Unicode.GetString(entryNameBytes);

                    modules.Add(new Module((IntPtr) entry.DllBase, entryFilePath, entryName));
                }
            }

            else
            {
                foreach (var entry in ReadPebEntries().Values)
                {
                    // Read the file path of the entry

                    var entryFilePathBytes = Memory.ReadBlock((IntPtr) entry.FullDllName.Buffer, entry.FullDllName.Length);

                    var entryFilePath = Encoding.Unicode.GetString(entryFilePathBytes);

                    // Read the name of the entry

                    var entryNameBytes = Memory.ReadBlock((IntPtr) entry.BaseDllName.Buffer, entry.BaseDllName.Length);

                    var entryName = Encoding.Unicode.GetString(entryNameBytes);

                    modules.Add(new Module((IntPtr) entry.DllBase, entryFilePath, entryName));
                }
            }

            return modules;
        }

19 View Source File : ChangeType.cs
License : MIT License
Project Creator : akasarto

public static T ChangeType<T>(this object @this, T defaultValue = default(T))
		{
			try
			{
				if (@this == null)
				{
					return defaultValue;
				}

				if (@this is T)
				{
					return (T)@this;
				}

				Type conversionType = typeof(T);

				// Nullables
				if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
				{
					conversionType = (new NullableConverter(conversionType)).UnderlyingType;
				}

				if (conversionType.IsEnum)
				{
					var enumStr = @this.ToString();

					// Clean the input string before attempting to convert.
					if (!string.IsNullOrWhiteSpace(enumStr))
					{
						enumStr = InvalidEnumValueChars.Replace(enumStr, string.Empty);
					}

					return (T)Enum.Parse(conversionType, enumStr, ignoreCase: true);
				}

				// String
				if (conversionType.Equals(typeof(string)))
				{
					return (T)((object)Convert.ToString(@this));
				}

				// Guid
				if (conversionType.Equals(typeof(Guid)))
				{
					var input = @this.ToString();

					if (string.IsNullOrWhiteSpace(input))
					{
						return defaultValue;
					}

					Guid output;
					if (Guid.TryParse(input, out output))
					{
						return (T)((object)output);
					}
				}

				// Bool
				if (conversionType.Equals(typeof(bool)))
				{
					return (T)((object)Convert.ToBoolean(@this));
				}

				// Datetime
				if (conversionType.Equals(typeof(DateTime)))
				{
					return (T)((object)DateTime.Parse(@this.ToString(), CultureInfo.CurrentCulture));
				}

				// TimeSpan
				if (conversionType.Equals(typeof(TimeSpan)))
				{
					return (T)((object)TimeSpan.Parse(@this.ToString(), CultureInfo.CurrentCulture));
				}

				// General
				return (T)Convert.ChangeType(@this, conversionType);
			}
			catch
			{
				return defaultValue;
			}
		}

19 View Source File : FilterSpecialChars.cs
License : MIT License
Project Creator : akasarto

public static string FilterSpecialChars(this string @this, string replacer = "", bool normalizeAccentuated = true)
		{
			if (string.IsNullOrWhiteSpace(@this))
			{
				return string.Empty;
			}

			if (normalizeAccentuated)
			{
				@this = @this.NormalizeAccentuation();
			}

			return SpecialChars.Replace(@this, replacer);
		}

19 View Source File : ToSlug.cs
License : MIT License
Project Creator : akasarto

public static string ToSlug(this Enum @this)
		{
			if (@this == null)
			{
				return string.Empty;
			}

			var enumString = NonInitialUpperCaseChars.Replace(@this.ToString(), ".");

			return enumString.ToSlug();
		}

19 View Source File : ColorPickerPopup.cs
License : MIT License
Project Creator : alelievr

void DrawHexComponents()
		{
			byte a = (byte)(int)(currentColor.a * 255);
			int hex = ColorUtils.ColorToHex(currentColor, false); //get color without alpha
			
			EditorGUIUtility.labelWidth = 80;
			EditorGUI.BeginChangeCheck();
			string hexColor = EditorGUILayout.TextField("Hex color", hex.ToString("X6"));
			if (EditorGUI.EndChangeCheck())
				a = 255;
			EditorGUIUtility.labelWidth = 0;
			Regex reg = new Regex(@"[^A-F0-9 -]");
			hexColor = reg.Replace(hexColor, "");
			hexColor = hexColor.Substring(0, Mathf.Min(hexColor.Length, 6));
			if (hexColor == "")
				hexColor = "0";
			hex = int.Parse(a.ToString("X2") + hexColor, System.Globalization.NumberStyles.HexNumber);
			currentColor = (SerializableColor)ColorUtils.HexToColor(hex, false);
		}

19 View Source File : Extension.cs
License : MIT License
Project Creator : AlenToma

internal static string CleanName(this string name)
        {
            return new Regex("[^a-zA-Z0-9,_]").Replace(name, "_");
        }

19 View Source File : XmlUtility.cs
License : MIT License
Project Creator : AlenToma

private static string ToXml(object o, ref string xml, bool addStart = true, string propName = "")
        {
            if (addStart)
                xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            var name = string.IsNullOrWhiteSpace(propName) ? new Regex("[^a-zA-Z]").Replace(o.GetType().Name, "") : propName;
            var quName = o.GetType().replacedemblyQualifiedName;

            if (o.GetType().IsInternalType())
            {
                if (o is byte[])
                    o = Convert.ToBase64String(o as byte[]);
                xml += $"<{name}>{o}</{name}>";
                return xml;
            }

            xml += $"<{name} FullName=\"{quName}\">";

            if (o is IList)
            {
                foreach (var item in (IList)o)
                    ToXml(item, ref xml, false);
            }
            else
            {
                foreach (var prop in DeepCloner.GetFastDeepClonerProperties(o.GetType()).Where(x => !x.ContainAttribute<XmlIgnore>()))
                {
                    var value = prop.GetValue(o);
                    if (value == null)
                        continue;
                    var zName = prop.Name;

                    if (value is byte[])
                        value = Convert.ToBase64String(value as byte[]);
                    if (value.GetType().IsInternalType())
                        xml += $"<{zName}>{value}</{zName}>";
                    else ToXml(value, ref xml, false, zName);
                }
            }

            xml += $"</{name}>";
            return xml;

        }

19 View Source File : MKMDatabaseManager.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public static void BulkInsertDataTable(string tableName, DataTable table, SQLiteConnection m_dbConnection)
    {
      try
      {
        var rgx = new Regex("[^a-zA-Z0-9]");


        using (var transaction = m_dbConnection.BeginTransaction())
        {
          var sql = new StringBuilder();

          sql.AppendFormat("INSERT INTO {0} (", tableName);

          var i = 0;

          var iQm = "";

          for (i = 0; i < table.Columns.Count; i++)
          {
            sql.AppendFormat(" \"{0}\"", table.Columns[i].ColumnName);

            iQm = iQm + "@" + rgx.Replace(table.Columns[i].ColumnName, "");

            if (i != table.Columns.Count - 1)
            {
              sql.Append(",");
              iQm += ", ";
            }
          }

          sql.Append(") VALUES (" + iQm + ")");

          var sSql = sql.ToString();

          foreach (DataRow dtRow in table.Rows)
          {
            var insertSQL = new SQLiteCommand(sSql, m_dbConnection);

            foreach (DataColumn dc in table.Columns)
              insertSQL.Parameters.Add(new SQLiteParameter("@" + rgx.Replace(dc.ColumnName, ""),
                  dtRow[dc].ToString()));

            //Console.WriteLine(dtRow[dc].ToString());

            insertSQL.ExecuteNonQuery();
          }

          transaction.Commit();
        }

      }
      catch (Exception Ex)
      {
        LogError("bulk-inserting data into the SQL database (MKMTool will still function correctly)", Ex.Message, false);
      }
    }

19 View Source File : HateoasUriProvider.cs
License : Apache License 2.0
Project Creator : alexz76

protected string GetFormatedPath(string path)
		{
			if (path == null)
			{
				return null;
			}

			if (path.StartsWith("/"))
			{
				var startReplaceRegex = new Regex("^(/)*");
				path = startReplaceRegex.Replace(path, string.Empty);
			}

			if (path.EndsWith("/"))
			{
				var endReplaceRegex = new Regex("(/)$");
				path = endReplaceRegex.Replace(path, string.Empty);
			}

			return path.ToLower();
		}

19 View Source File : HateoasCustomUriProvider.cs
License : Apache License 2.0
Project Creator : alexz76

private string ExtractTokenFromUrl(string path, IDictionary<string, object> routeValues)
		{
			var finalPath = new StringBuilder();
			var regex = new Regex(@"\[(?<token>\w*)\]");

			foreach (string part in path.Split("/", StringSplitOptions.RemoveEmptyEntries))
			{
				string replace = part;
				var match = regex.Match(part);
				if (match.Success)
				{
					var token = match.Groups["token"].Value;
					replace = regex.Replace(part, routeValues[token].ToString());
				}

				finalPath = finalPath.Append($"/{replace}");
			}

			return finalPath.ToString();
		}

19 View Source File : MQSigner.cs
License : MIT License
Project Creator : aliyunmq

static string CompressSpaces(string data)
        {
            if (data == null || !data.Contains(" "))
                return data;

            var compressed = CompressWhitespaceRegex.Replace(data, " ");
            return compressed;
        }

19 View Source File : DynamicUnionResolver.cs
License : Apache License 2.0
Project Creator : allenai

private static TypeInfo BuildType(Type type)
        {
            TypeInfo ti = type.GetTypeInfo();

            // order by key(important for use jump-table of switch)
            UnionAttribute[] unionAttrs = ti.GetCustomAttributes<UnionAttribute>().OrderBy(x => x.Key).ToArray();

            if (unionAttrs.Length == 0)
            {
                return null;
            }

            if (!ti.IsInterface && !ti.IsAbstract)
            {
                throw new MessagePackDynamicUnionResolverException("Union can only be interface or abstract clreplaced. Type:" + type.Name);
            }

            var checker1 = new HashSet<int>();
            var checker2 = new HashSet<Type>();
            foreach (UnionAttribute item in unionAttrs)
            {
                if (!checker1.Add(item.Key))
                {
                    throw new MessagePackDynamicUnionResolverException("Same union key has found. Type:" + type.Name + " Key:" + item.Key);
                }

                if (!checker2.Add(item.SubType))
                {
                    throw new MessagePackDynamicUnionResolverException("Same union subType has found. Type:" + type.Name + " SubType: " + item.SubType);
                }
            }

            Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
            using (MonoProtection.EnterRefEmitLock())
            {
                TypeBuilder typeBuilder = Dynamicreplacedembly.Value.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });

                FieldBuilder typeToKeyAndJumpMap = null; // Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>
                FieldBuilder keyToJumpMap = null; // Dictionary<int, int>

                // create map dictionary
                {
                    ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
                    typeToKeyAndJumpMap = typeBuilder.DefineField("typeToKeyAndJumpMap", typeof(Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>), FieldAttributes.Private | FieldAttributes.InitOnly);
                    keyToJumpMap = typeBuilder.DefineField("keyToJumpMap", typeof(Dictionary<int, int>), FieldAttributes.Private | FieldAttributes.InitOnly);

                    ILGenerator il = method.GetILGenerator();
                    BuildConstructor(type, unionAttrs, method, typeToKeyAndJumpMap, keyToJumpMap, il);
                }

                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Serialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                        null,
                        new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    BuildSerialize(type, unionAttrs, method, typeToKeyAndJumpMap, il);
                }

                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Deserialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                        type,
                        new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    BuildDeserialize(type, unionAttrs, method, keyToJumpMap, il);
                }

                return typeBuilder.CreateTypeInfo();
            }
        }

19 View Source File : MessagePackSerializerOptions.cs
License : Apache License 2.0
Project Creator : allenai

public virtual Type LoadType(string typeName)
        {
            Type result = Type.GetType(typeName, false);
            if (result == null && this.AllowreplacedemblyVersionMismatch)
            {
                string shortenedName = replacedemblyNameVersionSelectorRegex.Replace(typeName, string.Empty);
                if (shortenedName != typeName)
                {
                    result = Type.GetType(shortenedName, false);
                }
            }

            return result;
        }

19 View Source File : SVTXPainterUtils.cs
License : MIT License
Project Creator : alpacasking

public static string SanitizeForFileName(string name)
        {
            var reg = new Regex("[\\/:\\*\\?<>\\|\\\"]");
            return reg.Replace(name, "_");
        }

19 View Source File : TypeHelper.cs
License : MIT License
Project Creator : AlphaYu

public static string BuildTypeName(Type type)
        {
            return SubtractFullNameRegex.Replace(type.replacedemblyQualifiedName, "");
        }

19 View Source File : DefaultRedisProvider.cs
License : MIT License
Project Creator : AlphaYu

private string HandlePrefix(string prefix)
        {
            // Forbid
            if (prefix.Equals("*"))
                throw new ArgumentException("the prefix should not equal to *");

            // Don't start with *
            prefix = new System.Text.RegularExpressions.Regex("^\\*+").Replace(prefix, "");

            // End with *
            if (!prefix.EndsWith("*", StringComparison.OrdinalIgnoreCase))
                prefix = string.Concat(prefix, "*");

            return prefix;
        }

19 View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir

public static string RemoveNonNumbers(this string texto)
        {
            if (string.IsNullOrEmpty(texto.DefaultString()))
                return string.Empty;

            var regex = new Regex(@"[^\d]");
            return regex.Replace(texto, "");
        }

See More Examples