System.Text.RegularExpressions.Regex.Escape(string)

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

647 Examples 7

19 Source : JitDasmOptions.cs
with MIT License
from 0xd4d

static Regex CreateRegex(string wildcardString) {
			const RegexOptions flags = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Singleline;
			return new Regex("^" + Regex.Escape(wildcardString).Replace(@"\*", ".*").Replace(@"\?", ".") + "$", flags);
		}

19 Source : helpers.cs
with MIT License
from 91Act

public static bool Like(this string str, string pattern)
        {
            return new Regex(
                "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                RegexOptions.IgnoreCase | RegexOptions.Singleline
            ).IsMatch(str);
        }

19 Source : Wildcard.cs
with MIT License
from aabiryukov

public static string WildcardToRegex(string pattern)
        {
            if (pattern == null) throw new ArgumentNullException(nameof(pattern));

            // Remove whitespaces
            var items = pattern.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries);
            for(var i=0; i<items.Length; i++)
            {
                items[i] = "^" + Escape(items[i].Trim()).
                 Replace("\\*", ".*").
                 Replace("\\?", ".") + "$";
            }

            return string.Join("|", items);
        }

19 Source : V1Loader.cs
with MIT License
from Abdesol

static string ImportRegex(string expr, bool singleWord, bool? startOfLine)
		{
			StringBuilder b = new StringBuilder();
			if (startOfLine != null) {
				if (startOfLine.Value) {
					b.Append(@"(?<=(^\s*))");
				} else {
					b.Append(@"(?<!(^\s*))");
				}
			} else {
				if (singleWord)
					b.Append(@"\b");
			}
			for (int i = 0; i < expr.Length; i++) {
				char c = expr[i];
				if (c == '@') {
					++i;
					if (i == expr.Length)
						throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
					switch (expr[i]) {
						case 'C': // match whitespace or punctuation
							b.Append(@"[^\w\d_]");
							break;
						case '!': // negative lookahead
							{
							StringBuilder whatmatch = new StringBuilder();
							++i;
							while (i < expr.Length && expr[i] != '@') {
								whatmatch.Append(expr[i++]);
							}
							b.Append("(?!(");
							b.Append(Regex.Escape(whatmatch.ToString()));
							b.Append("))");
						}
						break;
						case '-': // negative lookbehind
							{
							StringBuilder whatmatch = new StringBuilder();
							++i;
							while (i < expr.Length && expr[i] != '@') {
								whatmatch.Append(expr[i++]);
							}
							b.Append("(?<!(");
							b.Append(Regex.Escape(whatmatch.ToString()));
							b.Append("))");
						}
						break;
						case '@':
							b.Append("@");
							break;
						default:
							throw new HighlightingDefinitionInvalidException("Unknown character in @ sequence.");
					}
				} else {
					b.Append(Regex.Escape(c.ToString()));
				}
			}
			if (singleWord)
				b.Append(@"\b");
			return b.ToString();
		}

19 Source : XmlHighlightingDefinition.cs
with MIT License
from Abdesol

public object VisitKeywords(XshdKeywords keywords)
			{
				if (keywords.Words.Count == 0)
					return Error(keywords, "Keyword group must not be empty.");
				foreach (string keyword in keywords.Words) {
					if (string.IsNullOrEmpty(keyword))
						throw Error(keywords, "Cannot use empty string as keyword");
				}
				StringBuilder keyWordRegex = new StringBuilder();
				// We can use "\b" only where the keyword starts/ends with a letter or digit, otherwise we don't
				// highlight correctly. (example: ILAsm-Mode.xshd with ".maxstack" keyword)
				if (keywords.Words.All(IsSimpleWord)) {
					keyWordRegex.Append(@"\b(?>");
					// (?> = atomic group
					// atomic groups increase matching performance, but we
					// must ensure that the keywords are sorted correctly.
					// "\b(?>in|int)\b" does not match "int" because the atomic group captures "in".
					// To solve this, we are sorting the keywords by descending length.
					int i = 0;
					foreach (string keyword in keywords.Words.OrderByDescending(w => w.Length)) {
						if (i++ > 0)
							keyWordRegex.Append('|');
						keyWordRegex.Append(Regex.Escape(keyword));
					}
					keyWordRegex.Append(@")\b");
				} else {
					keyWordRegex.Append('(');
					int i = 0;
					foreach (string keyword in keywords.Words) {
						if (i++ > 0)
							keyWordRegex.Append('|');
						if (char.IsLetterOrDigit(keyword[0]))
							keyWordRegex.Append(@"\b");
						keyWordRegex.Append(Regex.Escape(keyword));
						if (char.IsLetterOrDigit(keyword[keyword.Length - 1]))
							keyWordRegex.Append(@"\b");
					}
					keyWordRegex.Append(')');
				}
				return new HighlightingRule {
					Color = GetColor(keywords, keywords.ColorReference),
					Regex = CreateRegex(keywords, keyWordRegex.ToString(), XshdRegexType.Default)
				};
			}

19 Source : SearchStrategyFactory.cs
with MIT License
from Abdesol

static string ConvertWildcardsToRegex(string searchPattern)
		{
			if (string.IsNullOrEmpty(searchPattern))
				return "";

			StringBuilder builder = new StringBuilder();

			foreach (char ch in searchPattern) {
				switch (ch) {
					case '?':
						builder.Append(".");
						break;
					case '*':
						builder.Append(".*");
						break;
					default:
						builder.Append(Regex.Escape(ch.ToString()));
						break;
				}
			}

			return builder.ToString();
		}

19 Source : V1Loader.cs
with MIT License
from Abdesol

XshdSpan ImportSpan(XmlElement element)
		{
			XshdSpan span = new XshdSpan();
			if (element.HasAttribute("rule")) {
				span.RuleSetReference = new XshdReference<XshdRuleSet>(null, element.GetAttribute("rule"));
			}
			char escapeCharacter = ruleSetEscapeCharacter;
			if (element.HasAttribute("escapecharacter")) {
				escapeCharacter = element.GetAttribute("escapecharacter")[0];
			}
			span.Multiline = !(element.GetBoolAttribute("stopateol") ?? false);

			span.SpanColorReference = GetColorReference(element);

			span.BeginRegexType = XshdRegexType.IgnorePatternWhitespace;
			span.BeginRegex = ImportRegex(element["Begin"].InnerText,
										  element["Begin"].GetBoolAttribute("singleword") ?? false,
										  element["Begin"].GetBoolAttribute("startofline"));
			span.BeginColorReference = GetColorReference(element["Begin"]);

			string endElementText = string.Empty;
			if (element["End"] != null) {
				span.EndRegexType = XshdRegexType.IgnorePatternWhitespace;
				endElementText = element["End"].InnerText;
				span.EndRegex = ImportRegex(endElementText,
											element["End"].GetBoolAttribute("singleword") ?? false,
											null);
				span.EndColorReference = GetColorReference(element["End"]);
			}

			if (escapeCharacter != '\0') {
				XshdRuleSet ruleSet = new XshdRuleSet();
				if (endElementText.Length == 1 && endElementText[0] == escapeCharacter) {
					// ""-style escape
					ruleSet.Elements.Add(new XshdSpan {
						BeginRegex = Regex.Escape(endElementText + endElementText),
						EndRegex = ""
					});
				} else {
					// \"-style escape
					ruleSet.Elements.Add(new XshdSpan {
						BeginRegex = Regex.Escape(escapeCharacter.ToString()),
						EndRegex = "."
					});
				}
				if (span.RuleSetReference.ReferencedElement != null) {
					ruleSet.Elements.Add(new XshdImport { RuleSetReference = span.RuleSetReference });
				}
				span.RuleSetReference = new XshdReference<XshdRuleSet>(ruleSet);
			}
			return span;
		}

19 Source : SearchStrategyFactory.cs
with MIT License
from Abdesol

public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
		{
			if (searchPattern == null)
				throw new ArgumentNullException("searchPattern");
			RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;
			if (ignoreCase)
				options |= RegexOptions.IgnoreCase;

			switch (mode) {
				case SearchMode.Normal:
					searchPattern = Regex.Escape(searchPattern);
					break;
				case SearchMode.Wildcard:
					searchPattern = ConvertWildcardsToRegex(searchPattern);
					break;
			}
			try {
				Regex pattern = new Regex(searchPattern, options);
				return new RegexSearchStrategy(pattern, matchWholeWords);
			} catch (ArgumentException ex) {
				throw new SearchPatternException(ex.Message, ex);
			}
		}

19 Source : V1Loader.cs
with MIT License
from Abdesol

static XshdRule ImportMarkPrevNext(XmlElement el, bool markFollowing)
		{
			bool markMarker = el.GetBoolAttribute("markmarker") ?? false;
			string what = Regex.Escape(el.InnerText);
			const string identifier = @"[\d\w_]+";
			const string whitespace = @"\s*";

			string regex;
			if (markFollowing) {
				if (markMarker) {
					regex = what + whitespace + identifier;
				} else {
					regex = "(?<=(" + what + whitespace + "))" + identifier;
				}
			} else {
				if (markMarker) {
					regex = identifier + whitespace + what;
				} else {
					regex = identifier + "(?=(" + whitespace + what + "))";
				}
			}
			return new XshdRule {
				ColorReference = GetColorReference(el),
				Regex = regex,
				RegexType = XshdRegexType.IgnorePatternWhitespace
			};
		}

19 Source : DirectoryHelper.cs
with MIT License
from ABTSoftware

public static bool IsValidPath(string path, out string error)
        {
            error = null;
            switch (path)
            {
                case null: 
                    error = "Path can't be null";
                    return false;
                case "":
                    error = "";
                    return false;
            }

            if (path.Length < 3)
            {
                error = "Please set drive at least";
                return false;
            }

            string drive = path.Substring(0, 3);   // e.g. K:\

            var driveCheck = new Regex(@"^[a-zA-Z]:\\$");
            if (!driveCheck.IsMatch(drive))
            {
                error = @"Drive should be set in the following format: ""_:\"", where ""_"" is drive letter";
                return false;
            }

            if (!Directory.Exists(drive))
            {
                error = @"Drive " + drive + " not found or inaccessible";
                return false;
            }

            var strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
            strTheseAreInvalidFileNameChars += @":/?*" + "\"";

            var containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
            if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            {
                error = "The given path's format is not supported";
                return false;
            }

            return true;
        }

19 Source : CommandManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string[] StuffRawIntoParameters(string raw, string command, string[] parameters)
        {
            List<string> parametersRehash = new List<string>();
            var regex = new Regex(Regex.Escape(command));
            var newCmdLine = regex.Replace(raw, "", 1).TrimStart();
            parametersRehash.Add(newCmdLine);
            parametersRehash.AddRange(parameters);
            parameters = parametersRehash.ToArray();
            return parameters;
        }

19 Source : FileHandle.cs
with MIT License
from action-bi-toolkit

private static string ResolveDosFilePath(string name)
        {
            if (string.IsNullOrEmpty(name)) return null;

            var volumeNumberLocation = 0;
            for (var j = 0; j < 2 && volumeNumberLocation != -1; j++)
            {
                volumeNumberLocation = name.IndexOf('\\', volumeNumberLocation + 1);
            }

            if (volumeNumberLocation == -1)
            {
                volumeNumberLocation = name.Length;
            }

            var volumeNumber = name.Substring(0, volumeNumberLocation);
            if (DeviceMap.TryGetValue(volumeNumber, out var drive))
            {
                return Regex.Replace(name, Regex.Escape(volumeNumber), drive,
                    RegexOptions.IgnoreCase);
            }

            return null;
        }

19 Source : CustomCompletionItemMatcher.cs
with MIT License
from Actipro

protected override Regex GetRegex(string text) {
			// Make sure the text to highlight is surrounded with parenthesis so that SyntaxEditor can locate the captures
			return new Regex(String.Format("[\\._]({0})", Regex.Escape(text)), RegexOptions.IgnoreCase | RegexOptions.Singleline);
		}

19 Source : Utilities.cs
with MIT License
from ADeltaX

public static Regex ConvertWildcardsToRegEx(string pattern)
        {
            if (!pattern.Contains("."))
            {
                pattern += ".";
            }

            string query = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", "[^.]") + "$";
            return new Regex(query, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
        }

19 Source : SimpleHtmlHighlightedFragmentProvider.cs
with MIT License
from Adoxio

public string GetFragment(Doreplacedent doreplacedent)
		{
			if (doreplacedent == null)
			{
				throw new ArgumentNullException("doreplacedent");
			}

			var contentField = doreplacedent.GetField(_index.ContentFieldName);

			if (contentField == null || !contentField.IsStored)
			{
				return string.Empty;
			}

			var content = contentField.StringValue;

			var tokenStream = _index.replacedyzer.TokenStream(contentField.Name, new StringReader(content));

			var rawFragment = _highlighter.GetBestFragments(tokenStream, content, 1, "...");

			var bestFragment = Regex.Split(rawFragment, @"^\s*$", RegexOptions.Multiline)
				.OrderByDescending(f => Regex.Matches(f, Regex.Escape(_highlighterStartTag)).Count)
				.First();

			var fragment = bestFragment.Trim();

			if (string.IsNullOrEmpty(fragment))
			{
				return string.Empty;
			}

			return "… {0} …".FormatWith(fragment);
		}

19 Source : Mask.cs
with MIT License
from Adoxio

public virtual Regex ToRegex(RegexOptions options)
		{
			string pattern = Regex.Escape(_pattern);

			pattern = ReplaceWildcardsWithRegexEquivalent(pattern);
			pattern = ReplaceAttributesWithNamedCaptures(pattern);
			pattern = "^" + pattern + "$";

			return new Regex(pattern, options);
		}

19 Source : MoneyFormatter.cs
with MIT License
from Adoxio

private bool GetCurrencySymbolComesFirst()
		{
			return Regex.IsMatch(
				new decimal(1.00).ToString("C", _culture),
				string.Format(@"^\s*{0}", Regex.Escape(_culture.NumberFormat.CurrencySymbol)));
		}

19 Source : WildcardComparison.cs
with Apache License 2.0
from adrianiftode

internal static bool IsWildcardMatch(this string source, string wildcard)
        {
            if (string.IsNullOrEmpty(source))
            {
                throw new ArgumentException("Source cannot be null or an empty string.", nameof(source));
            }

            if (string.IsNullOrEmpty(wildcard))
            {
                throw new ArgumentException("Wildcard cannot be null or an empty string.", nameof(wildcard));
            }

            var pattern = WildcardToRegular(wildcard);
            return Regex.IsMatch(source, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

            static string WildcardToRegular(string value)
                => "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
        }

19 Source : PreviewUrlResolver.cs
with Apache License 2.0
from advanced-cms

private string GetAccessibleVirtualPath(VirtualPathData virtualPathData, PageData data, string language)
        {
            var virtualPath = virtualPathData.VirtualPath;
            var provider = this._providerManager.ProviderMap.GetProvider(data.ContentLink.ProviderName);
            var masterContent = (PageData)provider.GetScatteredContents(new[] {data.ContentLink.ToReferenceWithoutVersion()},
                new LanguageSelector(language ?? data.LanguageBranch())).FirstOrDefault();
            if (masterContent != null)
            {
                var urlSegment = data.URLSegment;
                var masterContentUrlSegment = masterContent.URLSegment;
                if (masterContentUrlSegment != urlSegment)
                {
                    var count = Regex.Matches(virtualPath, Regex.Escape(urlSegment)).Count;
                    // If there are multiple occurrences we should just skip the replace to avoid problems
                    if (count == 1)
                    {
                        virtualPath = virtualPath.Replace(urlSegment, masterContentUrlSegment);
                    }
                }
            }

            return virtualPath;
        }

19 Source : FileBackup.cs
with MIT License
from AkiniKites

private static IEnumerable<string> GetMatchingFiles(string path)
        {
            var filename = Path.GetFileName(path);
            var matcher = new Regex($"^{Regex.Escape(filename)}{GuidPattern}$", RegexOptions.IgnoreCase);
            var dir = Path.GetDirectoryName(path);
            if (String.IsNullOrEmpty(dir))
                dir = ".";

            if (Directory.Exists(dir))
            {
                foreach (var file in Directory.GetFiles(dir))
                {
                    if (matcher.IsMatch(Path.GetFileName(file)))
                        yield return file;
                }
            }
        }

19 Source : Heatmaster.cs
with MIT License
from AlexGyver

private bool WriteField(int device, char field, string value) {
      serialPort.WriteLine("[0:" + device + "]W" + field + ":" + value);
      for (int i = 0; i < 5; i++) {
        string s = ReadLine(200);
        Match match = Regex.Match(s, @"-\[0:" + 
          device.ToString(CultureInfo.InvariantCulture) + @"\]W" + 
          Regex.Escape(field.ToString(CultureInfo.InvariantCulture)) +
          ":" + value);
        if (match.Success)
          return true;
      }
      return false;
    }

19 Source : Heatmaster.cs
with MIT License
from AlexGyver

private string ReadField(int device, char field) {
      serialPort.WriteLine("[0:" + device + "]R" + field);
      for (int i = 0; i < 5; i++) {
        string s = ReadLine(200);
        Match match = Regex.Match(s, @"-\[0:" + 
          device.ToString(CultureInfo.InvariantCulture) + @"\]R" +
          Regex.Escape(field.ToString(CultureInfo.InvariantCulture)) + ":(.*)");
        if (match.Success) 
          return match.Groups[1].Value;
      }
      return null;
    }

19 Source : StringExtension.cs
with MIT License
from AlphaYu

public static bool IsLike([NotNull] this string @this, string pattern)
        {
            // Turn the pattern into regex pattern, and match the whole string with ^$
            var regexPattern = "^" + Regex.Escape(pattern) + "$";

            // Escape special character ?, #, *, [], and [!]
            regexPattern = regexPattern.Replace(@"\[!", "[^")
                .Replace(@"\[", "[")
                .Replace(@"\]", "]")
                .Replace(@"\?", ".")
                .Replace(@"\*", ".*")
                .Replace(@"\#", @"\d");

            return Regex.IsMatch(@this, regexPattern);
        }

19 Source : bindED.cs
with GNU General Public License v3.0
from alterNERDtive

private static string DetectBindsFile(string preset)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(_bindingsDir);
            FileInfo[] bindFiles = dirInfo.GetFiles()
                .Where(i => Regex.Match(i.Name, $@"^{Regex.Escape(preset)}\.[34]\.0\.binds$").Success)
                .OrderByDescending(p => p.Name).ToArray();

            if (bindFiles.Count() == 0)
            {
                bindFiles = dirInfo.GetFiles($"{preset}.binds");
                if (bindFiles.Count() == 0)
                {
                    throw new FileNotFoundException($"No bindings file found for preset '{preset}'. If this is a default preset, please change anything in Elite’s controls options.");
                }
            }

            return bindFiles[0].FullName;
        }

19 Source : TestBase.cs
with Apache License 2.0
from AmpScm

public char GetSvnStatus( string path )
        {   
            string output = this.RunCommand( "svn", "st --non-recursive \"" + path + "\"" );

            if ( output.Trim() == "" )
                return (char)0;

            string[] lines = output.Trim().Split( '\n' );
            Array.Sort( lines, new StringLengthComparer() );  
          
            string regexString = String.Format( @"(.).*\s{0}\s*", Regex.Escape(path) );
            Match match = Regex.Match( lines[0], regexString, RegexOptions.IgnoreCase );
            if ( match != Match.Empty )
                return match.Groups[1].ToString()[0];
            else 
            {
                replacedert.Fail( "TestBase.GetSvnStatus - Regex match failed: " + output );
                return (char)0; // not necessary, but compiler complains..
            }

        }

19 Source : Utils.cs
with MIT License
from Analogy-LogViewer

public static Regex Convert(string pattern)
        {
            if (pattern == null)
            {
                throw new ArgumentNullException();
            }
            pattern = pattern.Trim();
            if (pattern.Length == 0)
            {
                throw new ArgumentException("Pattern is empty.");
            }
            if (IllegalCharactersRegex.IsMatch(pattern))
            {
                throw new ArgumentException("Pattern contains illegal characters.");
            }
            bool hasExtension = CatchExtentionRegex.IsMatch(pattern);
            bool matchExact = false;
            if (HasQuestionMarkRegEx.IsMatch(pattern))
            {
                matchExact = true;
            }
            else if (hasExtension)
            {
                matchExact = CatchExtentionRegex.Match(pattern).Groups[1].Length != 3;
            }
            string regexString = Regex.Escape(pattern);
            regexString = "^" + Regex.Replace(regexString, @"\\\*", ".*");
            regexString = Regex.Replace(regexString, @"\\\?", ".");
            if (!matchExact && hasExtension)
            {
                regexString += NonDotCharacters;
            }
            regexString += "$";
            Regex regex = new Regex(regexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return regex;
        }

19 Source : FileUtils.cs
with MIT License
from AntonyCorbett

public static string CoerceValidFileName(string filename)
        {
            var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
            var invalidReStr = $@"[{invalidChars}]+";

            var reservedWords = new[]
            {
                "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
                "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
                "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
            };

            var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
            foreach (var reservedWord in reservedWords)
            {
                var reservedWordPattern = $"^{reservedWord}\\.";
                sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
            }

            return sanitisedNamePart;
        }

19 Source : Value.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var val = ArgToString(arguments, 0).TrimEnd(' ');
            double result = 0d;
            if (Regex.IsMatch(val, $"^[\\d]*({Regex.Escape(_groupSeparator)}?[\\d]*)?({Regex.Escape(_decimalSeparator)}[\\d]*)?[ ?% ?]?$"))
            {
                if (val.EndsWith("%"))
                {
                    val = val.TrimEnd('%');
                    result = double.Parse(val) / 100;
                }
                else
                {
                    result = double.Parse(val);
                }
                return CreateResult(result, DataType.Decimal);
            }
            if (double.TryParse(val, NumberStyles.Float, CultureInfo.CurrentCulture, out result))
            {
                return CreateResult(result, DataType.Decimal);
            }
            var timeSeparator = Regex.Escape(_timeSeparator);
            if (Regex.IsMatch(val, @"^[\d]{1,2}" + timeSeparator + @"[\d]{2}(" + timeSeparator + @"[\d]{2})?$"))
            {
                var timeResult = _timeValueFunc.Execute(val);
                if (timeResult.DataType == DataType.Date)
                {
                    return timeResult;
                }
            }
            var dateResult = _dateValueFunc.Execute(val);
            if (dateResult.DataType == DataType.Date)
            {
                return dateResult;
            }
            return CreateResult(ExcelErrorValue.Create(eErrorType.Value), DataType.ExcelError);
        }

19 Source : WildCardValueMatcher.cs
with Apache License 2.0
from Appdynamics

protected override int CompareStringToString(string s1, string s2)
        {
            if (s1.Contains("*") || s1.Contains("?"))
            {
                var regexPattern = Regex.Escape(s1);
                regexPattern = string.Format("^{0}$", regexPattern);
                regexPattern = regexPattern.Replace(@"\*", ".*");
                regexPattern = regexPattern.Replace(@"\?", ".");
                if (Regex.IsMatch(s2, regexPattern))
                {
                    return 0;
                }
            }
            return base.CompareStringToString(s1, s2);
        }

19 Source : PathUtils.cs
with MIT License
from aprilyush

public static string RemovePathInvalidChar(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                return filePath;
            var invalidChars = new string(Path.GetInvalidPathChars());
            string invalidReStr = $"[{Regex.Escape(invalidChars)}]";
            return Regex.Replace(filePath, invalidReStr, "");
        }

19 Source : RegexUtil.cs
with MIT License
from arbelatech

private static string Escape(string s)
        {
            return Regex.Escape(s);
        }

19 Source : Program.cs
with MIT License
from arcusmaximus

private static void PreloadResources<TResources>(ResourceManager resourceManager)
        {
            replacedembly replacedembly = typeof(TResources).replacedembly;
            FieldInfo resourceSetsField = typeof(ResourceManager).GetField("_resourceSets", BindingFlags.NonPublic | BindingFlags.Instance);
            Dictionary<string, ResourceSet> resourceSets = (Dictionary<string, ResourceSet>)resourceSetsField.GetValue(resourceManager);

            foreach (string resourceName in replacedembly.GetManifestResourceNames())
            {
                Match match = Regex.Match(resourceName, Regex.Escape(typeof(TResources).FullName) + @"\.([-\w]+)\.resources$");
                if (!match.Success)
                    continue;

                string culture = match.Groups[1].Value;
                using Stream stream = replacedembly.GetManifestResourceStream(resourceName);
                ResourceSet resSet = new ResourceSet(stream);
                resourceSets.Add(culture, resSet);
            }
        }

19 Source : ReplaceString.cs
with MIT License
from ardalis

public static string ReplaceString(this string text, string oldString, string newString, int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), "Count can not be negative");
            }
            else if (oldString is null)
            {
                throw new ArgumentException(nameof(oldString), "OldString can not be null");
            }
            else if (newString is null)
            {
                throw new ArgumentException(nameof(newString), "NewString can not be null");
            }

            Regex regex = new Regex(Regex.Escape(oldString));

            return regex.Replace(text, newString, count);
        }

19 Source : Extensions.cs
with GNU Affero General Public License v3.0
from arklumpus

public static string CoerceValidFileName(this string filename)
        {
            var invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
            var invalidReStr = string.Format(@"[{0}]+", invalidChars);

            var reservedWords = new[]
            {
                "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
                "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
                "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
            };

            var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
            foreach (var reservedWord in reservedWords)
            {
                var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
                sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
            }

            return sanitisedNamePart;
        }

19 Source : Parse_node_states.cs
with GNU Affero General Public License v3.0
from arklumpus

private static async void ShowPreview(MainWindow window, Dictionary<string, object> parameterValues)
        {
            if (window != null)
            {
                try
                {
                    int skipLines = (int)(double)parameterValues["Lines to skip:"];
                    string separatorString = (string)parameterValues["Separator:"];
                    bool separatorRegex = (bool)parameterValues["Regex"];

                    int attributeType = (int)parameterValues["Attribute type: "];

                    string attributeName = (string)parameterValues["Column header(s):"];
                    Attachment attachment = (Attachment)parameterValues["Data file:"];
                    int matchColumn = (int)(double)parameterValues["Match column:"];
                    string matchAttribute = (string)parameterValues["Match attribute:"];
                    string matchAttributeType = (string)parameterValues["Match attribute type:"];

                    bool useHeaderRow = (bool)parameterValues["Use first row as header"];

                    if (attachment != null)
                    {
                        Regex separator;

                        if (separatorRegex)
                        {
                            separator = new Regex(separatorString);
                        }
                        else
                        {
                            separator = new Regex(Regex.Escape(separatorString));
                        }

                        string[] lines = attachment.GetLines();

                        List<object[]> attributes = new List<object[]>();

                        string[] attributeNames;

                        if (useHeaderRow)
                        {
                            try
                            {
                                string[] splitLine = (from el in separator.Split(lines[skipLines]) where !string.IsNullOrEmpty(el) select el).ToArray();
                                attributeNames = splitLine;
                            }
                            catch
                            {
                                attributeNames = new string[0];
                            }
                        }
                        else
                        {
                            attributeNames = (from el in separator.Split(Regex.Unescape(attributeName)) where !string.IsNullOrEmpty(el) select el.Trim()).ToArray();
                        }

                        for (int i = skipLines + (useHeaderRow ? 1 : 0); i < lines.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(lines[i]))
                            {
                                string[] splitLine = (from el in separator.Split(lines[i]) where !string.IsNullOrEmpty(el) select el).ToArray();
                                if (splitLine.Length > matchColumn)
                                {
                                    object[] attribute = new object[splitLine.Length];
                                    for (int j = 0; j < splitLine.Length; j++)
                                    {
                                        if (attributeType == 0)
                                        {
                                            attribute[j] = splitLine[j];
                                        }
                                        else if (attributeType == 1)
                                        {
                                            if (double.TryParse(splitLine[j], out double parsed))
                                            {
                                                attribute[j] = parsed;
                                            }
                                            else
                                            {
                                                attribute[j] = double.NaN;
                                            }
                                        }
                                        else if (attributeType == 2)
                                        {
                                            if (double.TryParse(splitLine[j], out double parsed))
                                            {
                                                attribute[j] = parsed;
                                            }
                                            else
                                            {
                                                attribute[j] = splitLine[j];
                                            }
                                        }
                                    }

                                    attributes.Add(attribute);
                                }
                            }
                        }


                        ChildWindow previewWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = 14, Icon = window.Icon, Width = 800, Height = 450, replacedle = "Data preview", WindowStartupLocation = WindowStartupLocation.CenterOwner };

                        Grid windowGrid = new Grid() { Margin = new Thickness(10) };
                        windowGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                        windowGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                        windowGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                        windowGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                        previewWindow.Content = windowGrid;

                        Avalonia.Controls.Grid headerGrid = new Avalonia.Controls.Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 5) };
                        headerGrid.ColumnDefinitions.Add(new Avalonia.Controls.ColumnDefinition(0, Avalonia.Controls.GridUnitType.Auto));
                        headerGrid.ColumnDefinitions.Add(new Avalonia.Controls.ColumnDefinition(1, Avalonia.Controls.GridUnitType.Star));
                        headerGrid.Children.Add(new DPIAwareBox(GetIcon32) { Width = 32, Height = 32 });

                        {
                            Avalonia.Controls.TextBlock blk = new Avalonia.Controls.TextBlock() { FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)), Text = "Data preview", Margin = new Avalonia.Thickness(10, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                            Avalonia.Controls.Grid.SetColumn(blk, 1);
                            headerGrid.Children.Add(blk);
                        }

                        windowGrid.Children.Add(headerGrid);



                        StackPanel rowCountPanel = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 5), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
                        rowCountPanel.Children.Add(new TextBlock() { Text = "Number of rows to preview:", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                        NumericUpDown rowCountNud = new NumericUpDown() { Minimum = 1, Maximum = attributes.Count, Value = Math.Min(50, attributes.Count), Margin = new Thickness(5, 0, 0, 0), Width = 150, FormatString = "0" };
                        rowCountPanel.Children.Add(rowCountNud);
                        Grid.SetRow(rowCountPanel, 1);
                        windowGrid.Children.Add(rowCountPanel);

                        StackPanel legendPanel = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 5), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };

                        legendPanel.Children.Add(new Avalonia.Controls.Shapes.Rectangle() { Width = 12, Height = 12, Fill = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 78, 138)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });

                        legendPanel.Children.Add(new TextBlock() { Text = "String values", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 13, Margin = new Thickness(5, 0, 0, 0) });

                        legendPanel.Children.Add(new Avalonia.Controls.Shapes.Rectangle() { Width = 12, Height = 12, Fill = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(166, 55, 0)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(15, 0, 0, 0) });
                        legendPanel.Children.Add(new TextBlock() { Text = "Number values", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 13, Margin = new Thickness(5, 0, 0, 0) });

                        Grid.SetRow(legendPanel, 2);
                        windowGrid.Children.Add(legendPanel);

                        ScrollViewer scroller = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, Padding = new Avalonia.Thickness(0, 0, 16, 16), AllowAutoHide = false };
                        Grid.SetRow(scroller, 3);
                        windowGrid.Children.Add(scroller);

                        BuildPreviewTable(rowCountNud, attributes, matchColumn, attributeNames, scroller);

                        rowCountNud.ValueChanged += (s, e) =>
                        {
                            BuildPreviewTable(rowCountNud, attributes, matchColumn, attributeNames, scroller);
                        };

                        await previewWindow.ShowDialog2(window);
                    }
                    else
                    {
                        await new MessageBox("Attention!", "No attachment has been selected!").ShowDialog2(window);
                    }
                }
                catch (Exception ex)
                {
                    await new MessageBox("Error!", "An error occurred while loading the preview!\n" + ex.Message).ShowDialog2(window);
                }
            }

        }

19 Source : Parse_node_states.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            int skipLines = (int)(double)parameterValues["Lines to skip:"];
            string separatorString = (string)parameterValues["Separator:"];
            bool separatorRegex = (bool)parameterValues["Regex"];

            int attributeType = (int)parameterValues["Attribute type: "];

            string attributeName = (string)parameterValues["Column header(s):"];
            Attachment attachment = (Attachment)parameterValues["Data file:"];
            int matchColumn = (int)(double)parameterValues["Match column:"];
            string matchAttribute = (string)parameterValues["Match attribute:"];
            string matchAttributeType = (string)parameterValues["Match attribute type:"];
            bool useHeaderRow = (bool)parameterValues["Use first row as header"];

            if (attachment != null)
            {
                Regex separator;

                if (separatorRegex)
                {
                    separator = new Regex(separatorString);
                }
                else
                {
                    separator = new Regex(Regex.Escape(separatorString));
                }

                string[] lines = attachment.GetLines();

                Dictionary<string, object[]> attributes = new Dictionary<string, object[]>();

                string[] attributeNames;

                if (useHeaderRow)
                {
                    try
                    {
                        string[] splitLine = (from el in separator.Split(lines[skipLines]) where !string.IsNullOrEmpty(el) select el).ToArray();
                        attributeNames = splitLine;
                    }
                    catch
                    {
                        attributeNames = new string[0];
                    }
                }
                else
                {
                    attributeNames = (from el in separator.Split(Regex.Unescape(attributeName)) where !string.IsNullOrEmpty(el) select el.Trim()).ToArray();
                }

                for (int i = skipLines + (useHeaderRow ? 1 : 0); i < lines.Length; i++)
                {
                    if (!string.IsNullOrEmpty(lines[i]))
                    {
                        string[] splitLine = (from el in separator.Split(lines[i]) where !string.IsNullOrEmpty(el) select el).ToArray();
                        if (splitLine.Length > matchColumn)
                        {
                            object[] attribute = new object[splitLine.Length];
                            for (int j = 0; j < splitLine.Length; j++)
                            {
                                if (attributeType == 0)
                                {
                                    attribute[j] = splitLine[j];
                                }
                                else if (attributeType == 1)
                                {
                                    if (double.TryParse(splitLine[j], out double parsed))
                                    {
                                        attribute[j] = parsed;
                                    }
                                    else
                                    {
                                        attribute[j] = double.NaN;
                                    }
                                }
                                else if (attributeType == 2)
                                {
                                    if (double.TryParse(splitLine[j], out double parsed))
                                    {
                                        attribute[j] = parsed;
                                    }
                                    else
                                    {
                                        attribute[j] = splitLine[j];
                                    }
                                }
                            }

                            attributes.Add(splitLine[matchColumn - 1], attribute);
                        }
                    }
                }

                Dictionary<double, object[]> doubleAttributes = null;

                if (matchAttributeType == "Number")
                {
                    doubleAttributes = new Dictionary<double, object[]>();

                    foreach (KeyValuePair<string, object[]> kvp in attributes)
                    {
                        if (double.TryParse(kvp.Key, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double parsedKey) && !double.IsNaN(parsedKey))
                        {
                            doubleAttributes[parsedKey] = kvp.Value;
                        }
                    }
                }

                List<TreeNode> nodes = tree.GetChildrenRecursive();

                for (int i = 0; i < nodes.Count; i++)
                {
                    if (matchAttributeType == "Number")
                    {
                        if (nodes[i].Attributes.TryGetValue(matchAttribute, out object matchAttributeObject) && matchAttributeObject != null && matchAttributeObject is double matchAttributeValue && !double.IsNaN(matchAttributeValue))
                        {
                            if (doubleAttributes.TryGetValue(matchAttributeValue, out object[] attribute))
                            {
                                for (int j = 0; j < attribute.Length; j++)
                                {
                                    if (j != matchColumn - 1)
                                    {
                                        int attributeIndex = j;

                                        if (j >= matchColumn - 1 && matchColumn == 1 && attributeNames.Length < attribute.Length)
                                        {
                                            attributeIndex--;
                                        }

                                        nodes[i].Attributes[attributeNames[attributeIndex]] = attribute[j];
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (nodes[i].Attributes.TryGetValue(matchAttribute, out object matchAttributeObject) && matchAttributeObject != null && matchAttributeObject is string matchAttributeValue && !string.IsNullOrEmpty(matchAttributeValue))
                        {
                            if (attributes.TryGetValue(matchAttributeValue, out object[] attribute))
                            {
                                for (int j = 0; j < attribute.Length; j++)
                                {
                                    if (j != matchColumn - 1)
                                    {
                                        int attributeIndex = j;

                                        if (j >= matchColumn - 1 && matchColumn == 1 && attributeNames.Length < attribute.Length)
                                        {
                                            attributeIndex--;
                                        }

                                        if (attributeIndex < attributeNames.Length)
                                        {
                                            nodes[i].Attributes[attributeNames[attributeIndex]] = attribute[j];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : Url.cs
with MIT License
from arqueror

public static string SetQueryParameter(string url, string key, string value)
        {
            if (string.IsNullOrEmpty(value)) value = "";

            // Find existing parameter
            var existingMatch = Regex.Match(url, $"[?&]({Regex.Escape(key)}=?.*?)(?:&|/|$)");

            // Parameter already set to something
            if (existingMatch.Success)
            {
                var group = existingMatch.Groups[1];

                // Remove existing
                url = url.Remove(group.Index, group.Length);

                // Insert new one
                url = url.Insert(group.Index, $"{key}={value}");

                return url;
            }
            // Parameter hasn't been set yet
            else
            {
                // See if there are other parameters
                var hasOtherParams = url.IndexOf('?') >= 0;

                // Prepend either & or ? depending on that
                var separator = hasOtherParams ? '&' : '?';

                // replacedemble new query string
                return url + separator + key + '=' + value;
            }
        }

19 Source : Url.cs
with MIT License
from arqueror

public static string SetRouteParameter(string url, string key, string value)
        {
            if (string.IsNullOrEmpty(value)) value = "";

            // Find existing parameter
            var existingMatch = Regex.Match(url, $"/({Regex.Escape(key)}/?.*?)(?:/|$)");

            // Parameter already set to something
            if (existingMatch.Success)
            {
                var group = existingMatch.Groups[1];

                // Remove existing
                url = url.Remove(group.Index, group.Length);

                // Insert new one
                url = url.Insert(group.Index, $"{key}/{value}");

                return url;
            }
            // Parameter hasn't been set yet
            else
            {
                // replacedemble new query string
                return url + '/' + key + '/' + value;
            }
        }

19 Source : UnityDebugViewerEditorUtility.cs
with Apache License 2.0
from AsanCai

public static int GetIndexOfTargetString(string inputStr, string targetStr, int appearTimes = 1)
        {
            string regex = "((" + Regex.Escape(targetStr) + ").*?){" + appearTimes + "}";
            Match m = Regex.Match(inputStr, regex);

            if (m.Success)
            {
                return m.Groups[2].Captures[appearTimes - 1].Index;
            }
            else
            {
                return -1;
            }
        }

19 Source : Logger.cs
with MIT License
from Ashesh3

public static string GetCurrentStackMethod()
        {
            try
            {
                var tracePlain = Environment.StackTrace;
                var trace = tracePlain.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                var traceAt = trace.FirstOrDefault(x => Regex.IsMatch(x, $@"{Regex.Escape(nameof(SteamAccCreator))}\.(?!{Regex.Escape(nameof(Logger))}\.)\w+"));
                var at = "";
                var atRegex = Regex.Match(traceAt ?? "", @"at\s([^)]+\))", RegexOptions.IgnoreCase);
                if (atRegex.Success)
                    at = atRegex.Groups[1].Value;
                else
                    at = traceAt ?? "UNKNOWN";
                return at;
            }
            catch { return "UNKNOWN:ERR"; }
        }

19 Source : AMLUtils.cs
with MIT License
from AstroTechies

public static string SanitizeFilename(string name)
        {
            string invalidCharactersRegex = string.Format(@"([{0}]*\.+$)|([{0}]+)", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
            return Regex.Replace(name, invalidCharactersRegex, "_");
        }

19 Source : ParserTests.cs
with Apache License 2.0
from atifaziz

public static TheoryData<char, char?, char, string, bool,
                                 IEnumerable<string>,
                                 IEnumerable<(int LineNumber, string[] Fields)>,
                                 Type, string>
            GetData()
        {
            var type = MethodBase.GetCurrentMethod().DeclaringType;

            var config = new[] { "delimiter", "quote", "escape", "newline", "blanks" };
            var nils   = new[] { "null", "nil", "none", "undefined" };
            var proto  = new[] { new { ln = default(int), row = default(string[]) } };

            var data =
                from q in new[]
                {
                    from g in LineReader.ReadLinesFromStream(() => type.GetManifestResourceStream("Tests.md"))
                                        .Scan(new { Code = false, Line = default(string) },
                                              (s, line) => new
                                              {
                                                  Code = line.StartsWith("```", StringComparison.Ordinal) ? !s.Code : s.Code,
                                                  Line = line
                                              })
                                        .Skip(1) // skip seed
                                        .GroupAdjacent(e => e.Code)
                    select
                        from e in g.Skip(1) // skip "```"
                        select e.Line       // and keep just the lines
                }
                from e in q.Batch(4)
                select e.Pad(4) into e
                where e.All(s => s != null)
                select e.Fold((s, inp, _, exp) => new { Suppositions = string.Join(Environment.NewLine, s), Input = inp, Expected = exp }) into e
                let throws = '[' != e.Expected.FirstOrDefault()?.TrimStart()[0]
                select
                    config
                        .Select(p => Regex.Match(e.Suppositions, $@"(?<=\b{Regex.Escape(p)}( +is| *[=:]) *`)[^`]+(?=`)", RegexOptions.ExplicitCapture))
                        .Select(m => m.Success ? m.Value : null)
                        .Fold((d, q, esc, nl, blanks) => new
                        {
                            Delimiter  = d is string ds ? ds == @"\t" ? '\t' : ds[0] : ',',
                            Quote      = q == null
                                       ? '"'
                                       : nils.Contains(q, StringComparer.OrdinalIgnoreCase)
                                       ? (char?) null
                                       : q[0],
                            Escape     = esc?[0] ?? '"',
                            NewLine    = nl != null
                                       ? nils.Contains(nl, StringComparer.OrdinalIgnoreCase)
                                       ? null
                                       : Regex.Replace(nl, @"\\[rn]", m => m.Value[1] == 'r' ? "\r"
                                                                         : m.Value[1] == 'n' ? "\n"
                                                                         : throw new FormatException())
                                       : "\n",
                            SkipBlanks = "skip".Equals(blanks, StringComparison.OrdinalIgnoreCase),
                            e.Input,
                            Expected   = throws
                                       ? null
                                       : from r in Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(string.Join(Environment.NewLine, e.Expected), proto)
                                         select (r.ln, r.row),
                            Error      = throws
                                       ? Regex.Match(e.Expected.First(), @"^ *([^: ]+) *: *(.+)").BindNum((t, m) => new
                                         {
                                             Type    = t.Success
                                                     ? Type.GetType(t.Value, throwOnError: true)
                                                     : throw new Exception("Test exception type name missing."),
                                             Message = m.Success
                                                     ? m.Value.Trim()
                                                     : throw new Exception("Test exception message missing."),
                                         })
                                       : null,
                        })
                into e
                select (e.Delimiter, e.Quote, e.Escape, e.NewLine, e.SkipBlanks,
                        e.Input, e.Expected,
                        e.Error?.Type, e.Error?.Message);

            return data.ToTheoryData();
        }

19 Source : TextBoxInputBehavior.cs
with GNU General Public License v3.0
from atomex-me

private bool IsValidInput(string input)
        {
            switch (InputMode)
            {
                case TextBoxInputMode.None:
                    return true;

                case TextBoxInputMode.DigitInput:
                    return CheckIsDigit(input);

                case TextBoxInputMode.DecimalInput:
                    var culture = UseInvariantCulture
                            ? CultureInfo.InvariantCulture
                            : CultureInfo.CurrentCulture;

                    if (Regex.Matches(input, Regex.Escape(culture.NumberFormat.NumberDecimalSeparator)).Count > 1)
                        return false;

                    if (input.Contains("-"))
                    {
                        if (JustPositiveDecimalInput)
                            return false;

                        if (input.IndexOf("-", StringComparison.Ordinal) > 0)
                            return false;

                        if (input.ToCharArray().Count(x => x == '-') > 1)
                            return false;

                        if (input.Length == 1)
                            return true;
                    }                

                    return decimal.TryParse(input, ValidNumberStyles, culture, out _);

                default: throw new ArgumentException("Unknown TextBoxInputMode");
            }
        }

19 Source : XmlHighlightingDefinition.cs
with MIT License
from AvaloniaUI

public object VisitKeywords(XshdKeywords keywords)
            {
                if (keywords.Words.Count == 0)
                    return Error(keywords, "Keyword group must not be empty.");
                foreach (var keyword in keywords.Words)
                {
                    if (string.IsNullOrEmpty(keyword))
                        throw Error(keywords, "Cannot use empty string as keyword");
                }
                var keyWordRegex = new StringBuilder();
                // We can use "\b" only where the keyword starts/ends with a letter or digit, otherwise we don't
                // highlight correctly. (example: ILAsm-Mode.xshd with ".maxstack" keyword)
                if (keywords.Words.All(IsSimpleWord))
                {
                    keyWordRegex.Append(@"\b(?>");
                    // (?> = atomic group
                    // atomic groups increase matching performance, but we
                    // must ensure that the keywords are sorted correctly.
                    // "\b(?>in|int)\b" does not match "int" because the atomic group captures "in".
                    // To solve this, we are sorting the keywords by descending length.
                    var i = 0;
                    foreach (var keyword in keywords.Words.OrderByDescending(w => w.Length))
                    {
                        if (i++ > 0)
                            keyWordRegex.Append('|');
                        keyWordRegex.Append(Regex.Escape(keyword));
                    }
                    keyWordRegex.Append(@")\b");
                }
                else
                {
                    keyWordRegex.Append('(');
                    var i = 0;
                    foreach (var keyword in keywords.Words)
                    {
                        if (i++ > 0)
                            keyWordRegex.Append('|');
                        if (char.IsLetterOrDigit(keyword[0]))
                            keyWordRegex.Append(@"\b");
                        keyWordRegex.Append(Regex.Escape(keyword));
                        if (char.IsLetterOrDigit(keyword[keyword.Length - 1]))
                            keyWordRegex.Append(@"\b");
                    }
                    keyWordRegex.Append(')');
                }
                return new HighlightingRule
                {
                    Color = GetColor(keywords, keywords.ColorReference),
                    Regex = CreateRegex(keywords, keyWordRegex.ToString(), XshdRegexType.Default)
                };
            }

19 Source : SearchStrategyFactory.cs
with MIT License
from AvaloniaUI

public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
        {
            if (searchPattern == null)
                throw new ArgumentNullException(nameof(searchPattern));
            var options = RegexOptions.Multiline;
            if (ignoreCase)
                options |= RegexOptions.IgnoreCase;

            switch (mode)
            {
                case SearchMode.Normal:
                    searchPattern = Regex.Escape(searchPattern);
                    break;
                case SearchMode.Wildcard:
                    searchPattern = ConvertWildcardsToRegex(searchPattern);
                    break;
            }

            try
            {
                var pattern = new Regex(searchPattern, options);
                return new RegexSearchStrategy(pattern, matchWholeWords);
            }
            catch (ArgumentException ex)
            {
                throw new SearchPatternException(ex.Message, ex);
            }
        }

19 Source : SearchStrategyFactory.cs
with MIT License
from AvaloniaUI

private static string ConvertWildcardsToRegex(string searchPattern)
        {
            if (string.IsNullOrEmpty(searchPattern))
                return "";

            var builder = new StringBuilder();

            foreach (var ch in searchPattern)
            {
                switch (ch)
                {
                    case '?':
                        builder.Append(".");
                        break;
                    case '*':
                        builder.Append(".*");
                        break;
                    default:
                        builder.Append(Regex.Escape(ch.ToString()));
                        break;
                }
            }

            return builder.ToString();
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public Regex CreateRegex(bool ignoreCase = true)
        {
            ThrowOnError();

            if (Selection.HasFlag(WildcardSelection.Single))
                return CreateRegex(Selection.HasFlag(WildcardSelection.MultiWildcard) ? "^.*$" : "^.$", ignoreCase);

            var p = Regex.Escape(Text);
            if (Selection.HasFlag(WildcardSelection.MultiWildcard))
                p = p.Replace("\\*", ".*", StringComparison.InvariantCulture);

            if (Selection.HasFlag(WildcardSelection.SingleWildcard))
                p = p.Replace("\\?", ".", StringComparison.InvariantCulture);

            return CreateRegex($"^{p}$", ignoreCase);
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public string GetRegexPattern()
        {
            ThrowOnError();

            if (Selection.HasFlag(WildcardSelection.Single))
                return Selection.HasFlag(WildcardSelection.MultiWildcard) ? "^.*$" : "^.$";

            var p = Regex.Escape(Text);
            if (Selection.HasFlag(WildcardSelection.MultiWildcard))
                p = p.Replace("\\*", ".*", StringComparison.InvariantCulture);

            if (Selection.HasFlag(WildcardSelection.SingleWildcard))
                p = p.Replace("\\?", ".", StringComparison.InvariantCulture);

            return $"^{p}$";
        }

19 Source : EvaluateExpression.cs
with MIT License
from Avanade

private (int, int, ExpressionProperty, ExpressionProperty) GetOperator(string text)
        {
            ExpressionProperty operatorBetweenPropsAndValues = this._knowExpressionsTypes.Where(x => Regex.IsMatch(text, 
                $"{_regexAnything}{_regexWithWhiteSpace}{ Regex.Escape(x.Operator)}{_regexWithWhiteSpace}{_regexAnything}"))
                .FirstOrDefault();

            ExpressionProperty operatorExpression = default(ExpressionProperty);
            this._knowExpressionsTypes.ToList().ForEach(x => {

                if (Regex.IsMatch(text, $"{_regexAnything}{_regexWithWhiteSpace}{ Regex.Escape(x.Operator)}{_regexWithWhiteSpace}{_regexAnything}"))
                {
                    operatorExpression = new ExpressionProperty() { Operator = x.Operator, ExpressionType = x.ExpressionType };
                }
            });

            return (text.IndexOf(operatorBetweenPropsAndValues.Operator), operatorBetweenPropsAndValues.Operator.Length, operatorBetweenPropsAndValues, operatorExpression);
        }

19 Source : PathUpdater.cs
with MIT License
from awaescher

public void Remove(string value)
		{
			if (value == null)
				throw new ArgumentNullException(nameof(value));

			var pathVariables = Path.Get();

			if (string.IsNullOrEmpty(pathVariables))
				return;

			if (pathVariables.IndexOf(value, StringComparison.OrdinalIgnoreCase) == -1)
				return;

			pathVariables = Regex.Replace(pathVariables, $"\"?{Regex.Escape(value)}\"?;?", "", RegexOptions.IgnoreCase);

			if (pathVariables.EndsWith(";"))
				pathVariables = pathVariables.Substring(0, pathVariables.Length - 1);

			Path.Set(pathVariables);
		}

See More Examples