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

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

1194 Examples 7

19 Source : ArgHelper.cs
with MIT License
from bartoszlenar

public static IReadOnlyList<ArgPlaceholder> ExtractPlaceholders(string message)
        {
            ThrowHelper.NullArgument(message, nameof(message));

            string[] matches = CurlyBracketsRegex.Matches(message)
                .Cast<Match>()
                .Select(m => m.Value)
                .Distinct()
                .ToArray();

            var placeholders = new List<ArgPlaceholder>(matches.Length);

            foreach (var match in matches)
            {
                string[] parts = match.Split(Divider);

                var name = parts.FirstOrDefault();

                if (string.IsNullOrWhiteSpace(name))
                {
                    continue;
                }

                var placeholder = $"{{{match}}}";

                if (parts.Length == 1)
                {
                    placeholders.Add(new ArgPlaceholder
                    {
                        Placeholder = placeholder,
                        Name = name,
                        Parameters = EmptyParametersDictionary
                    });
                }
                else
                {
                    Dictionary<string, string> parameters = null;

                    var invalidPart = false;

                    for (var i = 1; i < parts.Length; ++i)
                    {
                        var item = parts.ElementAt(i);

                        if (!item.Contains(replacedignment))
                        {
                            invalidPart = true;

                            break;
                        }

                        string[] groups = item.Split(replacedignment).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray();

                        if (groups.Length != 2)
                        {
                            invalidPart = true;

                            break;
                        }

                        if (parameters == null)
                        {
                            parameters = new Dictionary<string, string>();
                        }

                        if (parameters.ContainsKey(groups.ElementAt(0)))
                        {
                            invalidPart = true;

                            break;
                        }

                        parameters.Add(groups.ElementAt(0), groups.ElementAt(1));
                    }

                    if (invalidPart)
                    {
                        continue;
                    }

                    placeholders.Add(new ArgPlaceholder
                    {
                        Placeholder = placeholder,
                        Name = name,
                        Parameters = parameters ?? EmptyParametersDictionary
                    });
                }
            }

            return placeholders;
        }

19 Source : MappingManager.cs
with MIT License
from Battlerax

public List<MappingObject> ParseDeleteObjectsFromString(string input) 
        {
            List<MappingObject> objectList = new List<MappingObject>();

            var objectPattern = @"API.DeleteObject\s*\(player,\s*new\s*Vector3\s*\(\s*(?<posX>-?[0-9.]*)\s*,\s*(?<posY>-?[0-9.]*)\s*,\s*(?<posZ>-?[0-9.]*)\)\s*,\s*(?<model>-?[0-9]+)\s*\);";
            var regex = new Regex(objectPattern);
            foreach (Match match in regex.Matches(input))
            {
                objectList.Add(new MappingObject(MappingObject.ObjectType.DeleteObject, Convert.ToInt32(match.Groups["model"].ToString()), new Vector3((float)Convert.ToDouble(match.Groups["posX"].ToString()), (float)Convert.ToDouble(match.Groups["posY"].ToString()), (float)Convert.ToDouble(match.Groups["posZ"].ToString())), new Vector3((float)Convert.ToDouble(match.Groups["rotX"].ToString()), (float)Convert.ToDouble(match.Groups["rotY"].ToString()), (float)Convert.ToDouble(match.Groups["rotZ"].ToString()))));
            }

            return objectList;
        }

19 Source : MappingManager.cs
with MIT License
from Battlerax

public List<MappingObject> ParseObjectsFromString(string input)
        {
            List<MappingObject> objectList = new List<MappingObject>();

            var objectPattern = @"NAPI.Object.CreateObject\s*\((?<model>-?[0-9]+)\s*,\s*new\s*Vector3\s*\(\s*(?<posX>-?[0-9.]*)\s*,\s*(?<posY>-?[0-9.]*)\s*,\s*(?<posZ>-?[0-9.]*)\)\s*,\s*new\s*Vector3\s*\(\s*(?<rotX>-?[0-9.]*)\s*,\s*(?<rotY>-?[0-9.]*)\s*,\s*(?<rotZ>-?[0-9.]*)\s*\)\s*\)";
            var regex = new Regex(objectPattern);
            foreach(Match match in regex.Matches(input))
            {
                objectList.Add(new MappingObject(MappingObject.ObjectType.CreateObject, Convert.ToInt32(match.Groups["model"].ToString()), new Vector3((float)Convert.ToDouble(match.Groups["posX"].ToString()), (float)Convert.ToDouble(match.Groups["posY"].ToString()), (float)Convert.ToDouble(match.Groups["posZ"].ToString())), new Vector3((float)Convert.ToDouble(match.Groups["rotX"].ToString()), (float)Convert.ToDouble(match.Groups["rotY"].ToString()), (float)Convert.ToDouble(match.Groups["rotZ"].ToString()))));
            }

            return objectList;
        }

19 Source : AsagiThreadConsumer.cs
with MIT License
from bbepis

private static string GenerateExifColumnData(Post post)
		{
			var exifJson = new JObject();

			if (!string.IsNullOrWhiteSpace(post.Comment))
			{
				var exifMatch = ExifRegex.Match(post.Comment);
				if (exifMatch.Success)
				{
					string data = exifMatch.Groups[1].Value;

					data = data.Replace("<tr><td colspan=\"2\"></td></tr><tr>", "");

					var exifDataMatches = ExifDataRegex.Matches(data);

					foreach (Match match in exifDataMatches)
					{
						string key = match.Groups[1].Value;
						string value = match.Groups[2].Value;
						exifJson[key] = value;
					}
				}

				var drawMatch = DrawRegex.Match(post.Comment);
				if (drawMatch.Success)
				{
					exifJson["Time"] = drawMatch.Groups[1].Value;
					exifJson["Painter"] = drawMatch.Groups[2].Value;
					exifJson["Source"] = drawMatch.Groups["source"].Success ? CleanComment(drawMatch.Groups["source"].Value) : null;
				}
			}

			if (post.UniqueIps.HasValue)
				exifJson["uniqueIps"] = post.UniqueIps.Value;

			if (post.Since4Preplaced.HasValue)
				exifJson["since4preplaced"] = post.Since4Preplaced.Value;

			if (post.TrollCountry != null)
				exifJson["trollCountry"] = post.TrollCountry;

			if (exifJson.Count == 0)
				return null;

			return exifJson.ToString(Formatting.None);
		}

19 Source : NumericUpDown.cs
with Apache License 2.0
from beckzhu

private string GetAnyNumberFromText(string text)
        {
            var matches = RegexStringFormatNumber.Matches(text);
            if (matches.Count > 0)
            {
                return matches[0].Value;
            }
            return text;
        }

19 Source : SteamLibrary.cs
with GNU General Public License v3.0
from beeradmoore

public async Task<List<Game>> ListGamesAsync()
        {
            _loadedGames.Clear();
            _loadedDLSSGames.Clear();

            // If we don't detect a steam install patg return an empty list.
            var installPath = GetInstallPath();
            if (String.IsNullOrWhiteSpace(installPath))
            {
                return new List<Game>();
            }

            // I hope this runs on a background thread. 
            // Tasks are whack.
            return await Task.Run<List<Game>>(() =>
            {
                var games = new List<Game>();

                // Base steamapps folder contains libraryfolders.vdf which has references to other steamapps folders.
                // All of these folders contain appmanifest_[some_id].acf which contains information about the game.
                // We parse all of these files with jank regex, rather than building a parser.
                // If we ever need to this page probably contains info on how to do that, https://developer.valvesoftware.com/wiki/KeyValues

                var baseSteamAppsFolder = Path.Combine(installPath, "steamapps");

                var libraryFolders = new List<string>();
                libraryFolders.Add(Helpers.PathHelpers.NormalizePath(baseSteamAppsFolder));

                var libraryFoldersFile = Path.Combine(baseSteamAppsFolder, "libraryfolders.vdf");
                if (File.Exists(libraryFoldersFile))
                {
                    try
                    {
                        var libraryFoldersFileText = File.ReadAllText(libraryFoldersFile);

                        var regex = new Regex(@"^([ \t]*)""(.*)""([ \t]*)""(?<path>.*)""$", RegexOptions.Multiline);
                        var matches = regex.Matches(libraryFoldersFileText);
                        if (matches.Count > 0)
                        {
                            foreach (Match match in matches)
                            {
                                // This is weird, but for some reason some libraryfolders.vdf are formatted very differnetly than others.
                                var path = match.Groups["path"].ToString();
                                if (Directory.Exists(path))
                                {
                                    libraryFolders.Add(Helpers.PathHelpers.NormalizePath(Path.Combine(path, "steamapps")));
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        // TODO: Report
                        System.Diagnostics.Debug.WriteLine($"ERROR: Unable to parse libraryfolders.vdf, {err.Message}");
                    }
                }

                // Makes sure all library folders are unique.
                libraryFolders = libraryFolders.Distinct().ToList();

                foreach (var libraryFolder in libraryFolders)
                {
                    if (Directory.Exists(libraryFolder))
                    {
                        var appManifests = Directory.GetFiles(libraryFolder, "appmanifest_*.acf");
                        foreach (var appManifest in appManifests)
                        {
                            var game = GetGameFromAppManifest(appManifest);
                            if (game != null)
                            {
                                games.Add(game);
                            }
                        }
                    }
                }
                games.Sort();
                _loadedGames.AddRange(games);
                _loadedDLSSGames.AddRange(games.Where(g => g.HasDLSS == true));

                return games;
            });
        }

19 Source : SteamLibrary.cs
with GNU General Public License v3.0
from beeradmoore

internal Game GetGameFromAppManifest(string appManifestPath)
        {
            try
            {
                var appManifest = File.ReadAllText(appManifestPath);
                var game = new Game();

                var regex = new Regex(@"^([ \t]*)""name""([ \t]*)""(?<name>.*)""$", RegexOptions.Multiline);
                var matches = regex.Matches(appManifest);
                if (matches.Count == 0)
                {
                    return null;
                }

                game.replacedle = matches[0].Groups["name"].ToString();

                regex = new Regex(@"^([ \t]*)""installdir""([ \t]*)""(?<installdir>.*)""$", RegexOptions.Multiline);
                matches = regex.Matches(appManifest);
                if (matches.Count == 0)
                {
                    return null;
                }

                var installDir = matches[0].Groups["installdir"].ToString();

                var baseDir = Path.GetDirectoryName(appManifestPath);

                game.InstallPath = Path.Combine(baseDir, "common", installDir);


                regex = new Regex(@"^([ \t]*)""appid""([ \t]*)""(?<appid>.*)""$", RegexOptions.Multiline);
                matches = regex.Matches(appManifest);
                if (matches.Count == 0)
                {
                    return null;
                }
                game.HeaderImage = $"https://steamcdn-a.akamaihd.net/steam/apps/{matches[0].Groups["appid"]}/library_600x900_2x.jpg"; // header.jpg";

                game.DetectDLSS();
                return game;
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine($"Error GetGameFromAppManifest: {err.Message}");
                return null;
            }
        }

19 Source : Helpers.cs
with MIT License
from Beffyman

private static string ConvertFromNullable(string type, out bool wasNullable)
		{
			var matches = NULLABLE_MATCHER.Matches(type);
			if (matches.Count > 0)
			{
				type = matches[matches.Count - 1].Groups[2].Value;
				wasNullable = true;
			}
			else
			{
				wasNullable = false;
			}

			return type;
		}

19 Source : Command.cs
with Apache License 2.0
from BeichenDream

public static string CommandExecution(string cmdtext) {
            Type type = typeof(Mysql.Command);
            Regex regex = new Regex("\\S+");
            MatchCollection match = regex.Matches(cmdtext);
            if (match.Count<2)
            {
                return "操作不存在";
            }
            
            string MethodName = Thread.CurrentThread.CurrentCulture.TextInfo.ToreplacedleCase(match[0].Value) + Thread.CurrentThread.CurrentCulture.TextInfo.ToreplacedleCase(match[1].Value);
            object[] value = new object[match.Count-2];
            MethodInfo  methodInfo= type.GetMethod(MethodName,BindingFlags.Static|BindingFlags.Public);
            if (methodInfo != null)
            {
                MethodBase methodBase = methodInfo.GetBaseDefinition();
                ParameterInfo[] parameterInfos = methodBase.GetParameters();
                if (parameterInfos.Length == value.Length) {
                    for (int i = 0; i < value.Length; i++)
                    {
                        try
                        {
                           
                            value[i] = Convert.ChangeType(match[i + 2].Value, parameterInfos[i].ParameterType);
                        }
                        catch (Exception e)
                        {

                            return "参数类型不匹配 E:"+e.Message;
                        }
                    }
                    try
                    {
                        return (string)methodInfo.Invoke(type, value);
                        
                    }
                    catch (Exception e)
                    {
                        return "方法返回值有误 E:"+e.Message;
                    }
                  

                }
                else
                {
                    return "参数不满足";
                }

            }
            else {
                return "方法不存在";
            }
            
        }

19 Source : Command.cs
with Apache License 2.0
from BeichenDream

public static string CommandExecution(string cmdtext) {
            Type type = typeof(Mysql.Command);
            Regex regex = new Regex("\\S+");
            MatchCollection match = regex.Matches(cmdtext);
            if (match.Count<2)
            {
                return "操作不存在";
            }
            
            string MethodName = Thread.CurrentThread.CurrentCulture.TextInfo.ToreplacedleCase(match[0].Value) + Thread.CurrentThread.CurrentCulture.TextInfo.ToreplacedleCase(match[1].Value);
            object[] value = new object[match.Count-2];
            MethodInfo  methodInfo= type.GetMethod(MethodName,BindingFlags.Static|BindingFlags.Public);
            if (methodInfo != null)
            {
                MethodBase methodBase = methodInfo.GetBaseDefinition();
                ParameterInfo[] parameterInfos = methodBase.GetParameters();
                if (parameterInfos.Length == value.Length) {
                    for (int i = 0; i < value.Length; i++)
                    {
                        try
                        {
                           
                            value[i] = Convert.ChangeType(match[i + 2].Value, parameterInfos[i].ParameterType);
                        }
                        catch (Exception)
                        {

                            return "参数类型不匹配";
                        }
                    }
                    try
                    {
                        return (string)methodInfo.Invoke(type, value);
                        
                    }
                    catch (Exception)
                    {
                        return "方法返回值有误";
                    }
                  

                }
                else
                {
                    return "参数不满足";
                }

            }
            else {
                return "方法不存在";
            }
            
        }

19 Source : ChatlogFormatter.cs
with GNU General Public License v3.0
from BigETI

public static string Format(string text, EChatlogFormatType formatType, bool showColorCodes, bool showColored, bool showTimestamp)
        {
            StringBuilder ret = new StringBuilder();
            Regex regex = null;
            try
            {
                switch (formatType)
                {
                    case EChatlogFormatType.Plain:
                        string plain_text = ((text == null) ? "" : text);
                        if (!showColorCodes)
                        {
                            regex = new Regex(@"\{([0-9a-f]{6})\}", RegexOptions.IgnoreCase);
                            plain_text = regex.Replace(plain_text, "");
                        }
                        if (!showTimestamp)
                        {
                            regex = new Regex(@"\[[0-9]{2}:[0-9]{2}:[0-9]{2}\][^\S\n]*");
                            plain_text = regex.Replace(plain_text, "");
                        }
                        ret.Append(plain_text);
                        break;

                    case EChatlogFormatType.RTF:
                        string rtf_escaped_text = ((text == null) ? "" : text.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}"));
                        int rtf_color_index = 2;
                        Dictionary<int, Tuple<Color, int>> color_table = new Dictionary<int, Tuple<Color, int>>
                        {
                            {
                                0xFFFFFF,
                                new Tuple<Color, int>(Color.FromArgb(255, 255, 255), 1)
                            },
                            {
                                0x333333,
                                new Tuple<Color, int>(Color.FromArgb(51, 51, 51), 2)
                            }
                        };
                        MatchCollection matches = null;
                        regex = new Regex(@"\\\{([0-9a-f]{6})\\\}", RegexOptions.IgnoreCase);
                        matches = regex.Matches(rtf_escaped_text);
                        ret.Append(@"{\rtf1{\colortbl ;\red255\green255\blue255;\red51\green51\blue51;");
                        foreach (Match match in matches)
                        {
                            if (match.Groups.Count > 1)
                            {
                                try
                                {
                                    int color_code = Convert.ToInt32(match.Groups[1].Value, 16);
                                    Color color = Color.FromArgb((color_code >> 16) & 0xFF, (color_code >> 8) & 0xFF, color_code & 0xFF);
                                    if (!(color_table.ContainsKey(color_code)))
                                    {
                                        color_table.Add(color_code, new Tuple<Color, int>(color, ++rtf_color_index));
                                        if (showColored)
                                        {
                                            ret.Append(@"\red" + ((int)(color.R)) + @"\green" + ((int)(color.G)) + @"\blue" + ((int)(color.B)) + ";");
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.Error.WriteLine(e);
                                }
                            }
                            string upper_match = match.Value.ToUpper();
                            if (match.Value != upper_match)
                            {
                                rtf_escaped_text = rtf_escaped_text.Replace(match.Value, upper_match);
                            }
                        }
                        if (!showTimestamp)
                        {
                            try
                            {
                                regex = new Regex(@"\[[0-9]{2}:[0-9]{2}:[0-9]{2}\][^\S\n]*");
                                rtf_escaped_text = regex.Replace(rtf_escaped_text, "");
                            }
                            catch (Exception e)
                            {
                                Console.Error.WriteLine(e);
                            }
                        }
                        ret.Append(@"}\highlight2");
                        string[] rtf_lines = rtf_escaped_text.Replace("\r", "").Split('\n');
                        if (rtf_lines != null)
                        {
                            foreach (string line in rtf_lines)
                            {
                                string new_line = line;
                                ret.AppendLine(@"\cf1");
                                foreach (KeyValuePair<int, Tuple<Color, int>> pair in color_table)
                                {
                                    new_line = new_line.Replace(@"\{" + string.Format("{0:X6}", pair.Key) + @"\}", (showColored ? (Environment.NewLine + @"\cf" + pair.Value.Item2 + Environment.NewLine) : "") + (showColorCodes ? (@"\{" + string.Format("{0:X}", pair.Key) + @"\}") : ""));
                                }
                                ret.AppendLine(new_line);
                                ret.AppendLine(@"\par");
                            }
                        }
                        ret.Append(Environment.NewLine);
                        ret.Append("}");
                        break;

                    case EChatlogFormatType.HTMLSnippet:
                    case EChatlogFormatType.HTML:
                        if (formatType == EChatlogFormatType.HTML)
                        {
                            ret.Append("<!DOCTYPE html><head><replacedle>San Andreas Multiplayer last chatlog</replacedle><body style=\"background-color: #333333; color: #ffffff;\">");
                        }
                        try
                        {
                            regex = new Regex(@"\{([0-9a-f]{6})\}", RegexOptions.IgnoreCase);
                            if (regex != null)
                            {
                                string html_encoded_text = ((text == null) ? "" : HttpUtility.HtmlEncode(text).Replace("\r", ""));
                                string[] html_lines = html_encoded_text.Split('\n');
                                if (html_lines != null)
                                {
                                    foreach (string line in html_lines)
                                    {
                                        string new_line = line;
                                        matches = regex.Matches(line);
                                        if (matches != null)
                                        {
                                            foreach (Match match in matches)
                                            {
                                                if (match.Groups.Count > 1)
                                                {
                                                    new_line = new_line.Replace(match.Value, (showColored ? ("<span style=\"color: #" + match.Groups[1].Value.ToLower() + ";\">") : "") + (showColorCodes ? (match.Value) : ""));
                                                }
                                            }
                                            ret.Append(new_line);
                                            for (int i = 0; i < matches.Count; i++)
                                            {
                                                ret.Append("</span>");
                                            }
                                        }
                                        else
                                        {
                                            ret.Append(new_line);
                                        }
                                        ret.Append("<br />");
                                    }
                                }
                                if (!showTimestamp)
                                {
                                    try
                                    {
                                        regex = new Regex(@"\[[0-9]{2}:[0-9]{2}:[0-9]{2}\][^\S\n]*");
                                        html_encoded_text = ret.ToString();
                                        ret.Clear();
                                        ret.Append(regex.Replace(html_encoded_text, ""));
                                    }
                                    catch (Exception e)
                                    {
                                        Console.Error.WriteLine(e);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(e);
                        }
                        if (formatType == EChatlogFormatType.HTML)
                        {
                            ret.Append("</body></html>");
                        }
                        break;
                }
            }
            catch (Exception e)
            {
                ret.Clear();
                Console.Error.WriteLine(e);
            }
            return ret.ToString();
        }

19 Source : Lrc.cs
with GNU General Public License v3.0
from Bililive

public static Lrc InitLrc(string LrcText)
        {
            Lrc lrc = new Lrc();
            Dictionary<double, string> dicword = new Dictionary<double, string>();

            string[] lines = LrcText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

            foreach (string line in lines)
            {
                if (line.StartsWith("[ti:"))
                {
                    lrc.replacedle = SplitInfo(line);
                }
                else if (line.StartsWith("[ar:"))
                {
                    lrc.Artist = SplitInfo(line);
                }
                else if (line.StartsWith("[al:"))
                {
                    lrc.Album = SplitInfo(line);
                }
                else if (line.StartsWith("[by:"))
                {
                    lrc.LrcBy = SplitInfo(line);
                }
                else if (line.StartsWith("[offset:"))
                {
                    lrc.Offset = SplitInfo(line);
                }
                else
                {
                    try
                    {
                        Regex regexword = new Regex(@".*\](.*)");
                        Match mcw = regexword.Match(line);
                        string word = mcw.Groups[1].Value;
                        if (word.Replace(" ", "") == "")
                            continue; // 如果为空歌词则跳过不处理
                        Regex regextime = new Regex(@"\[([0-9.:]*)\]", RegexOptions.Compiled);
                        MatchCollection mct = regextime.Matches(line);
                        foreach (Match item in mct)
                        {
                            double time = TimeSpan.Parse("00:" + item.Groups[1].Value).TotalSeconds;
                            dicword.Add(time, word);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            lrc.LrcWord = dicword.OrderBy(t => t.Key).ToDictionary(t => t.Key, p => p.Value);
            return lrc;
        }

19 Source : StartCommand.cs
with MIT License
from BionicFramework

private static int UpdateStartup(ProjectInfo projectInfo) {
      try {
        var all = File.ReadAllText(StartupPath);
        all = $"using BionicExtensions.Attributes;\n{all}";

        var matches = ServiceRegEx.Matches(all);
        var firstEntry = matches[0].Groups[1].Value;
        var browserName = matches[0].Groups[2].Value.Trim().Trim(Environment.NewLine.ToCharArray());

        var newServices =
          $"{firstEntry}\n            InjectableAttribute.RegisterInjectables({browserName});";

        using (var file = new StreamWriter(File.Create(StartupPath))) {
          file.Write(all.Replace(firstEntry, newServices));
        }
      }
      catch (Exception e) {
        Logger.Error($"Failed to update Startup.cs: {e.Message}");
        return 1;
      }

      return 0;
    }

19 Source : CssParser.cs
with MIT License
from BlazorComponent

public void Read(string cascadingStyleSheet)
        {
            this.StyleSheet = cascadingStyleSheet;

            if (string.IsNullOrEmpty(cascadingStyleSheet))
                return;

            MatchCollection matchList = rStyles.Matches(Regex.Replace(cascadingStyleSheet, CssComments, string.Empty));
            foreach (Match item in matchList)
            {
                if (item?.Groups[SelectorKey]?.Captures?[0] != null && !string.IsNullOrEmpty(item.Groups[SelectorKey].Value))
                {
                    string strSelector = item.Groups[SelectorKey].Captures[0].Value.Trim();
                    var style = new List<KeyValuePair<string, string>>();

                    for (int i = 0; i < item.Groups[NameKey].Captures.Count; i++)
                    {
                        string clreplacedName = item.Groups[NameKey].Captures[i].Value;
                        string value = item.Groups[ValueKey].Captures[i].Value;

                        if (string.IsNullOrEmpty(clreplacedName) || string.IsNullOrEmpty(value))
                            continue;

                        clreplacedName = clreplacedName.TrimWhiteSpace();
                        value = value.TrimWhiteSpace();

                        if (!string.IsNullOrEmpty(clreplacedName) && !string.IsNullOrEmpty(value))
                        {
                            style.Add(new KeyValuePair<string, string>(clreplacedName, value));
                        }
                    }

                    this.Add(new KeyValuePair<string, List<KeyValuePair<string, string>>>(strSelector, style));
                }
            }
        }

19 Source : LoadThemeStyle.cs
with MIT License
from BlazorExtensions

private ICollection<ThemingInstruction> splitStyles(string styles)
        {
            var result = new List<ThemingInstruction>();

            if (string.IsNullOrEmpty(styles))
            {
                var pos = 0; // Current position in styles.

                var matches = _themeTokenRegex.Matches(styles);
                for (int i = 0; i < matches.Count; i++)
                {

                    var match = matches[i];
                    var matchIndex = match.Index;
                    if (matchIndex > pos)
                    {
                        result.Add(new ThemingInstruction()
                        {
                            RawString = styles.Substring(pos, match.Length)
                        });
                    }

                    result.Add(new ThemingInstruction
                    {
                        Theme = match.Groups[1].Value,
                        DefaultValue = match.Groups[2].Value
                    });
                    // index of the first character after the current match
                    pos = match.Index;
                }
                // Push the rest of the string after the last match.
                result.Add(new ThemingInstruction
                {
                    RawString = styles.Substring(pos)
                });
            }
            return result;

        }

19 Source : FamistudioTextFile.cs
with MIT License
from BleuBleu

private static string SplitLine(string line, ref Dictionary<string, string> parameters)
        {
            parameters.Clear();

            var nameSeparated = NameRegex.Match(line);

            if (nameSeparated.Success)
            {
                var type = nameSeparated.Groups[1].Value;
                var attributes = nameSeparated.Groups[2].Value;

                // Ensure that everything following the type looks like an attribute.
                if (string.IsNullOrWhiteSpace(AttributeRegex.Replace(attributes, "")))
                {
                    foreach (Match match in AttributeRegex.Matches(attributes))
                    {
                        var key = match.Groups[1].Value;
                        var value = match.Groups[2].Value.Replace("\"\"", "\"");

                        parameters[key] = value;
                    }

                    return type;
                }
            }

            return null;
        }

19 Source : GPOGroupTasks.cs
with GNU General Public License v3.0
from BloodHoundAD

private static async Task<List<GroupAction>> ProcessGPOTmpl(string basePath, string gpoDomain)
        {
            var actions = new List<GroupAction>();
            var templatePath = $"{basePath}\\MACHINE\\Microsoft\\Windows NT\\SecEdit\\GptTmpl.inf";

            //Check the file exists
            if (File.Exists(templatePath))
            {
                using (var reader = new StreamReader(new FileStream(templatePath, FileMode.Open, FileAccess.Read)))
                {
                    //Read the file, and read it to the end
                    var content = await reader.ReadToEndAsync();

                    // Check if our regex matches
                    var memberMatch = MemberRegex.Match(content);

                    if (memberMatch.Success)
                    {
                        //If we have a match, split the lines
                        var memberText = memberMatch.Groups[1].Value;
                        var memberLines = Regex.Split(memberText.Trim(), @"\r\n|\r|\n");

                        //Loop over the lines that matched our regex
                        foreach (var memberLine in memberLines)
                        {
                            //Check if the Key regex matches (S-1-5.*_memberof=blah)
                            var keyMatch = KeyRegex.Match(memberLine);

                            var key = keyMatch.Groups[1].Value.Trim();
                            var val = keyMatch.Groups[2].Value.Trim();

                            //Figure out which pattern matches
                            var leftMatch = MemberLeftRegex.Match(key);
                            var rightMatches = MemberRightRegex.Matches(val);

                            //Scenario 1: Members of a local group are explicitly set
                            if (leftMatch.Success)
                            {
                                var extracted = ExtractRid.Match(leftMatch.Value);
                                var rid = int.Parse(extracted.Groups[1].Value);
                                if (Enum.IsDefined(typeof(LocalGroupRids), rid))
                                {
                                    //Loop over the members in the match, and try to convert them to SIDs
                                    foreach (var member in val.Split(','))
                                    {
                                        var (success, sid, type) = await GetSid(member.Trim('*'), gpoDomain);
                                        if (!success)
                                            continue;
                                        actions.Add(new GroupAction
                                        {
                                            Target = GroupActionTarget.RestrictedMember,
                                            Action = GroupActionOperation.Add,
                                            TargetSid = sid,
                                            TargetType = type,
                                            TargetRid = (LocalGroupRids)rid
                                        });
                                    }
                                }

                            }

                            //Scenario 2: A group has been set as memberOf to one of our local groups
                            var index = key.IndexOf("MemberOf", StringComparison.CurrentCultureIgnoreCase);
                            if (rightMatches.Count > 0 && index > 0)
                            {
                                var sid = key.Trim('*').Substring(0, index - 3).ToUpper();
                                var type = LdapTypeEnum.Unknown;
                                //If the member starts with s-1-5, try to resolve the SID, else treat it as an account name
                                if (!sid.StartsWith("S-1-5", StringComparison.OrdinalIgnoreCase))
                                {
                                    var (success, aSid, lType) = await ResolutionHelpers.ResolveAccountNameToSidAndType(sid, gpoDomain);
                                    if (!success)
                                    {
                                        (success, aSid, lType) = await ResolutionHelpers.ResolveAccountNameToSidAndType($"{sid}$", gpoDomain);
                                        sid = !success ? null : aSid;
                                    }
                                    else
                                        sid = aSid;

                                    type = lType;
                                }
                                else
                                {
                                    var (aSid, lType) = await ResolutionHelpers.ResolveSidAndGetType(sid, gpoDomain);
                                    sid = aSid;
                                    type = lType;
                                }

                                if (sid == null)
                                    continue;

                                // Loop over matches and add the actions appropriately
                                foreach (var match in rightMatches)
                                {
                                    var rid = int.Parse(ExtractRid.Match(match.ToString()).Groups[1].Value);
                                    if (!Enum.IsDefined(typeof(LocalGroupRids), rid)) continue;

                                    var targetGroup = (LocalGroupRids)rid;
                                    actions.Add(new GroupAction
                                    {
                                        Target = GroupActionTarget.RestrictedMemberOf,
                                        Action = GroupActionOperation.Add,
                                        TargetRid = targetGroup,
                                        TargetSid = sid,
                                        TargetType = type
                                    });
                                }
                            }
                        }
                    }
                }
            }

            return actions;
        }

19 Source : CreateCharacterHandler.cs
with GNU General Public License v3.0
from BlowaXD

protected override async Task Handle(CharNewPacketBase packet, ISession session)
        {
            long accountId = session.Account.Id;
            byte slot = packet.Slot;
            string characterName = packet.Name;

            if (slot > 3)
            {
                return;
            }

            if (await _characterService.GetByAccountIdAndSlotAsync(session.Account.Id, slot) != null)
            {
                Log.Warn($"[CREATE_CHARACTER] SLOT_ALREADY_TAKEN {slot}");
                return;
            }

            var rg = new Regex(@"^[\u0021-\u007E\u00A1-\u00AC\u00AE-\u00FF\u4E00-\u9FA5\u0E01-\u0E3A\u0E3F-\u0E5B\u002E]*$");
            if (rg.Matches(characterName).Count != 1)
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = _gameLanguageService.GetLanguage(PlayerMessages.CHARACTER_NAME_INVALID, session.Language)
                });
                Log.Warn($"[CREATE_CHARACTER] INVALID_NAME {characterName}");
                return;
            }

            CharacterDto character = await _characterService.GetActiveByNameAsync(characterName);
            if (character != null)
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = _gameLanguageService.GetLanguage(PlayerMessages.CHARACTER_NAME_ALREADY_TAKEN, session.Language)
                });
                Log.Warn($"[CREATE_CHARACTER] INVALID_NAME {characterName}");
                return;
            }

            CharacterDto newCharacter = _characterService.GetCreationCharacter();

            newCharacter.Clreplaced = CharacterClreplacedType.Adventurer;
            newCharacter.Gender = packet.Gender;
            newCharacter.HairColor = packet.HairColor;
            newCharacter.HairStyle = packet.HairStyle;
            newCharacter.Name = characterName;
            newCharacter.Slot = slot;
            newCharacter.AccountId = accountId;
            newCharacter.MinilandMessage = "Welcome";
            newCharacter.State = CharacterState.Active;
            await _characterService.SaveAsync(newCharacter);
            Log.Info($"[CHARACTER_CREATE] {newCharacter.Name} | Account : {session.Account.Name}");
            await _screenLoader.Handle(session);
        }

19 Source : CreateCharacterWrestlerHandler.cs
with GNU General Public License v3.0
from BlowaXD

protected override async Task Handle(CharNewWrestlerPacketBase packet, ISession session)
        {
            long accountId = session.Account.Id;
            byte slot = packet.Slot;
            string characterName = packet.Name;

            if (slot > 3)
            {
                return;
            }

            if (slot != 3)
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = "invalid_slot_wrestler"
                });
                Log.Warn($"[CREATE_CHARACTER] INVALID_SLOT_WRESTLER {slot}");
                return;
            }

            if (!_characterService.GetActiveByAccountId(session.Account.Id).Any(s => s.Level >= 80))
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = "invalid_lvl_wrestler"
                });
                Log.Warn("[CREATE_CHARACTER] INVALID_LVL_WRESTLER");
                return;
            }

            if (await _characterService.GetByAccountIdAndSlotAsync(session.Account.Id, slot) != null)
            {
                Log.Warn($"[CREATE_CHARACTER] SLOT_ALREADY_TAKEN {slot}");
                return;
            }

            var rg = new Regex(@"^[\u0021-\u007E\u00A1-\u00AC\u00AE-\u00FF\u4E00-\u9FA5\u0E01-\u0E3A\u0E3F-\u0E5B\u002E]*$");
            if (rg.Matches(characterName).Count != 1)
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = "invalid_charname"
                });
                Log.Warn($"[CREATE_CHARACTER] INVALID_NAME {characterName}");
                return;
            }

            CharacterDto character = await _characterService.GetActiveByNameAsync(characterName);
            if (character != null)
            {
                await session.SendPacketAsync(new InfoPacket
                {
                    Message = "Already_taken"
                });
                Log.Warn($"[CREATE_CHARACTER] INVALID_NAME {characterName}");
                return;
            }

            CharacterDto newCharacter = _characterService.GetCreationCharacter();

            newCharacter.Clreplaced = CharacterClreplacedType.Wrestler;
            newCharacter.Gender = packet.Gender;
            newCharacter.HairColor = packet.HairColor;
            newCharacter.HairStyle = packet.HairStyle;
            newCharacter.Name = characterName;
            newCharacter.Slot = slot;
            newCharacter.AccountId = accountId;
            newCharacter.MinilandMessage = "Welcome";
            newCharacter.State = CharacterState.Active;
            await _characterService.SaveAsync(newCharacter);
            Log.Info($"[CHARACTER_CREATE] {newCharacter.Name} | Account : {accountId}");
            await _screenLoader.Handle(session);
        }

19 Source : GdalOGR2OGR.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            string srcFileLocation = string.Empty;
            DA.GetData<string>(0, ref srcFileLocation);

            string dstFileLocation = string.Empty;
            DA.GetData<string>(1, ref dstFileLocation);

            string options = string.Empty;
            DA.GetData<string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");
            string[] ogr2ogrOptions = re.Matches(options).Cast<Match>().Select(m => m.Value).ToArray();

            string srcInfo = string.Empty;
            string dstInfo = string.Empty;
            string dstOutput = string.Empty;

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.OGR.Ogr.RegisterAll();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look here for more information about options:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/ogr2ogr.html");

            if (!string.IsNullOrEmpty(srcFileLocation))
            {
                using (Dataset src = Gdal.OpenEx(srcFileLocation, 0, null, null, null))
                {
                    if (src == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + srcFileLocation);
                    }

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (File.Exists(dstFileLocation))
                        {
                            if (options.Contains("-overwrite"))
                            {
                                File.Delete(dstFileLocation);
                                Dataset dst = Gdal.wrapper_GDALVectorTranslateDestName(dstFileLocation, src, new GDALVectorTranslateOptions(ogr2ogrOptions), null, null);
                                dst.Dispose();
                                dstInfo = string.Join("\r\n", OGRInfo(dstFileLocation));
                                dstOutput = dstFileLocation;
                            }
                            else
                            {
                                dstInfo = string.Join("\r\n", OGRInfo(dstFileLocation));
                                dstOutput = dstFileLocation;
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, dstFileLocation + " already exists. Include '-overwrite' in options to replace it.");
                            }
                        }
                        else
                        {
                            Dataset dst = Gdal.wrapper_GDALVectorTranslateDestName(dstFileLocation, src, new GDALVectorTranslateOptions(ogr2ogrOptions), null, null);
                            dst.Dispose();
                            dstInfo = string.Join("\r\n", OGRInfo(dstFileLocation));
                            dstOutput = dstFileLocation;
                        }

                    }

                    src.Dispose();
                    srcInfo = string.Join("\r\n", OGRInfo(srcFileLocation));
                }
            }

            DA.SetData(0, srcInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }

19 Source : GdalPoligonize.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            string datasourceFileLocation = string.Empty;
            DA.GetData<string>(0, ref datasourceFileLocation);

            string dstFileLocation = string.Empty;
            DA.GetData<string>(1, ref dstFileLocation);

            string options = string.Empty;
            DA.GetData<string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");
            string[] translateOptions = re.Matches(options).Cast<Match>().Select(m => m.Value).ToArray();

            string datasourceInfo = string.Empty;
            string dstInfo = string.Empty;
            string dstOutput = string.Empty;


            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdal_polygonize.html");

            if (!string.IsNullOrEmpty(datasourceFileLocation))
            {
                using (Dataset datasource = Gdal.Open(datasourceFileLocation, Access.GA_ReadOnly))
                {
                    if (datasource == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + datasourceFileLocation);
                    }

                    SpatialReference sr = new SpatialReference(datasource.GetProjection());

                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP = new SpatialReference(datasource.GetGCPProjection());
                    string projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  " +
                            "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        //sr.SetWellKnownGeogCS("WGS84");
                    }

                    ///Get info about image
                    List<string> infoOptions = new List<string> {
                    "-stats"
                    };
                    datasourceInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            ///https://github.com/OSGeo/gdal/issues/813
                            ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                            ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                            var ptr = new[] { Dataset.getCPtr(datasource).Handle };
                            var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                            try
                            {
                                var dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                                Dataset dst = Gdal.wrapper_GDALWarpDestName(dstFileLocation, 1, dss, new GDALWarpAppOptions(translateOptions), null, null);
                                if (dst == null)
                                {
                                    throw new Exception("GdalWarp failed: " + Gdal.GetLastErrorMsg());
                                }

                                dstInfo = Gdal.GDALInfo(dst, new GDALInfoOptions(infoOptions.ToArray()));
                                dst.Dispose();
                                dstOutput = dstFileLocation;
                            }
                            finally
                            {
                                if (gcHandle.IsAllocated)
                                    gcHandle.Free();
                            }

                        }
                    }
                    datasource.Dispose();
                }
            }

            DA.SetData(0, datasourceInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);

        }

19 Source : GdalTranslate.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            string datasourceFileLocation = string.Empty;
            DA.GetData<string>(0, ref datasourceFileLocation);

            string dstFileLocation = string.Empty;
            DA.GetData<string>(1, ref dstFileLocation);

            string options = string.Empty;
            DA.GetData<string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");
            string[] translateOptions = re.Matches(options).Cast<Match>().Select(m => m.Value).ToArray();

            string datasourceInfo = string.Empty;
            string dstInfo = string.Empty;
            string dstOutput = string.Empty;

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdal_translate.html");

            if (!string.IsNullOrEmpty(datasourceFileLocation))
            {
                using (Dataset datasource = Gdal.Open(datasourceFileLocation, Access.GA_ReadOnly))
                {
                    if (datasource == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + datasourceFileLocation);
                    }

                    SpatialReference sr = new SpatialReference(datasource.GetProjection());

                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP = new SpatialReference(datasource.GetGCPProjection());
                    string projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  " +
                            "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        //sr.SetWellKnownGeogCS("WGS84");
                    }

                    ///Get info about image
                    List<string> infoOptions = new List<string> {
                    "-stats"
                    };
                    datasourceInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            Dataset dst = Gdal.wrapper_GDALTranslate(dstFileLocation, datasource, new GDALTranslateOptions(translateOptions), null, null);
                            dstInfo = Gdal.GDALInfo(dst, new GDALInfoOptions(infoOptions.ToArray()));
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                    }
                    datasource.Dispose();
                }
            }

            DA.SetData(0, datasourceInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }

19 Source : GdalWarp.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            string datasourceFileLocation = string.Empty;
            DA.GetData<string>(0, ref datasourceFileLocation);

            string dstFileLocation = string.Empty;
            DA.GetData<string>(1, ref dstFileLocation);

            string options = string.Empty;
            DA.GetData<string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");
            string[] translateOptions = re.Matches(options).Cast<Match>().Select(m => m.Value).ToArray();

            string datasourceInfo = string.Empty;
            string dstInfo = string.Empty;
            string dstOutput = string.Empty;


            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdalwarp.html");

            if (!string.IsNullOrEmpty(datasourceFileLocation))
            {
                using (Dataset datasource = Gdal.Open(datasourceFileLocation, Access.GA_ReadOnly))
                {
                    if (datasource == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + datasourceFileLocation);
                    }

                    SpatialReference sr = new SpatialReference(datasource.GetProjection());

                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP = new SpatialReference(datasource.GetGCPProjection());
                    string projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  " +
                            "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        //sr.SetWellKnownGeogCS("WGS84");
                    }

                    ///Get info about image
                    List<string> infoOptions = new List<string> {
                    "-stats"
                    };
                    datasourceInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            ///https://github.com/OSGeo/gdal/issues/813
                            ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                            ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                            var ptr = new[] { Dataset.getCPtr(datasource).Handle };
                            var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                            try
                            {
                                var dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                                Dataset dst = Gdal.wrapper_GDALWarpDestName(dstFileLocation, 1, dss, new GDALWarpAppOptions(translateOptions), null, null);
                                if (dst == null)
                                {
                                    throw new Exception("GdalWarp failed: " + Gdal.GetLastErrorMsg());
                                }

                                dstInfo = Gdal.GDALInfo(dst, new GDALInfoOptions(infoOptions.ToArray()));
                                dst.Dispose();
                                dstOutput = dstFileLocation;
                            }
                            finally
                            {
                                if (gcHandle.IsAllocated)
                                    gcHandle.Free();
                            }

                        }
                    }
                    datasource.Dispose();
                }
            }

            DA.SetData(0, datasourceInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);

        }

19 Source : NetworkQuery.cs
with GNU General Public License v3.0
from blueminder

public static string GetExternalIP()
        {
            try
            {
                string externalIP;
                externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
                externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                             .Matches(externalIP)[0].ToString();
                return externalIP;
            }
            catch { return null; }
        }

19 Source : ParserTestBase.cs
with Apache License 2.0
from blushingpenguin

public static BehaviourTestData ParseBehaviourFixture(string ftlPath, string ftl)
        {
            var expected =
                String.Join("\n", s_reDirective.Matches(ftl)
                    .Select(x => x.Groups[1].Value)) + "\n";
            var source = s_reDirective.Replace(ftl, "");
            return new BehaviourTestData()
            {
                TestName = Path.GetFileNameWithoutExtension(ftlPath),
                Expected = expected,
                Source = source
            };
        }

19 Source : ParserTestBase.cs
with Apache License 2.0
from blushingpenguin

static FtlWithDirectives ProcessFtlWithDirectives(string ftl)
        {
            return new FtlWithDirectives()
            {
                Directives = s_reDirective.Matches(ftl).Select(x => x.Captures[0].Value),
                Ftl = s_reDirective.Replace(ftl, "")
            };
        }

19 Source : ColumnMapCollection.cs
with GNU General Public License v3.0
from bonarr

public ColumnMapCollection OrderParameters(DbCommand command)
        {
            if (command.CommandType == CommandType.Text && Count > 0)
            {
                string commandTypeString = command.GetType().ToString();
                if (commandTypeString.Contains("Oracle") || commandTypeString.Contains("OleDb"))
                {
                    ColumnMapCollection columns = new ColumnMapCollection();

                    // Find all @Parameters contained in the sql statement
                    string paramPrefix = commandTypeString.Contains("Oracle") ? ":" : "@";
                    string regexString = string.Format(@"{0}[\w-]+", paramPrefix);
                    Regex regex = new Regex(regexString);
                    foreach (Match m in regex.Matches(command.CommandText))
                    {
                        ColumnMap matchingColumn = Find(c => string.Concat(paramPrefix, c.ColumnInfo.Name.ToLower()) == m.Value.ToLower());
                        if (matchingColumn != null)
                            columns.Add(matchingColumn);
                    }

                    return columns;
                }
            }

            return this;
        }

19 Source : Expansive.cs
with GNU General Public License v3.0
from bonarr

public static string Expand(this string source, params string[] args)
        {
            var output = source;
            var tokens = new List<string>();
            var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
            var calls = new Stack<string>();
            string callingToken = null;

            while (pattern.IsMatch(output))
            {
                foreach (Match match in pattern.Matches(output))
                {
                    var token = _patternStyle.TokenReplaceFilter(match.Value);
                    var tokenIndex = 0;
                    if (!tokens.Contains(token))
                    {
                        tokens.Add(token);
                        tokenIndex = tokens.Count - 1;
                    }
                    else
                    {
                        tokenIndex = tokens.IndexOf(token);
                    }
                    output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}");
                }
            }
            var newArgs = new List<string>();
            foreach (var arg in args)
            {
                var newArg = arg;
                var tokenPattern = new Regex(_patternStyle.TokenFilter(string.Join("|", tokens)));
                while (tokenPattern.IsMatch(newArg))
                {
                    foreach (Match match in tokenPattern.Matches(newArg))
                    {
                        var token = _patternStyle.TokenReplaceFilter(match.Value);
                        if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken));
                        calls.Push(string.Format("{0}:{1}", callingToken, token));
                        callingToken = token;
                        newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]);
                    }

                }
                newArgs.Add(newArg);
            }
            return string.Format(output, newArgs.ToArray());
        }

19 Source : Expansive.cs
with GNU General Public License v3.0
from bonarr

private static string Explode(this string source, Regex pattern, PatternStyle patternStyle, Func<string, string> expansionFactory, TreeNode<string> parent)
        {
            var output = source;
            while (output.HasChildren(pattern))
            {
                foreach (Match match in pattern.Matches(source))
                {
                    var child = match.Value;
                    var token = patternStyle.TokenReplaceFilter(match.Value);

                    var thisNode = parent.Children.Add(token);

                    // if we have already encountered this token in this call tree, we have a circular reference
                    if (thisNode.CallTree.Contains(token))
                        throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}",
                                                                           token,
                                                                           string.Join("->", thisNode.CallTree.ToArray().Reverse()), token));

                    // expand this match
                    var expandedValue = expansionFactory(token);

                    // Replace the match with the expanded value
                    child = Regex.Replace(child, patternStyle.OutputFilter(match.Value), expandedValue);

                    // Recursively expand the child until we no longer encounter nested tokens (or hit a circular reference)
                    child = child.Explode(pattern, patternStyle, expansionFactory, thisNode);

                    // finally, replace the match in the output with the fully-expanded value
                    output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child);
                }
            }
            return output;
        }

19 Source : 069_quality_proper.cs
with GNU General Public License v3.0
from bonarr

private string GetNewFormat(string currentFormat)
        {
            var matches = QualityreplacedleRegex.Matches(currentFormat);
            var result = currentFormat;

            foreach (Match match in matches)
            {
                var tokenMatch = GetTokenMatch(match);
                var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); ;

                if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t)))
                {
                    qualityFullToken = string.Format("quality{0}full", tokenMatch.Separator);
                }
                else if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsUpper(t)))
                {
                    qualityFullToken = string.Format("QUALITY{0}FULL", tokenMatch.Separator);
                }

                result = result.Replace(match.Groups["token"].Value, qualityFullToken);
            }

            return result;
        }

19 Source : RssParser.cs
with GNU General Public License v3.0
from bonarr

public static long ParseSize(string sizeString, bool defaultToBinaryPrefix)
        {
            if (sizeString.All(char.IsDigit))
            {
                return long.Parse(sizeString);
            }

            var match = ParseSizeRegex.Matches(sizeString);

            if (match.Count != 0)
            {
                var value = decimal.Parse(Regex.Replace(match[0].Groups["value"].Value, "\\,", ""), CultureInfo.InvariantCulture);

                var unit = match[0].Groups["unit"].Value.ToLower();

                switch (unit)
                {
                    case "kb":
                        return ConvertToBytes(Convert.ToDouble(value), 1, defaultToBinaryPrefix);
                    case "mb":
                        return ConvertToBytes(Convert.ToDouble(value), 2, defaultToBinaryPrefix);
                    case "gb":
                        return ConvertToBytes(Convert.ToDouble(value), 3, defaultToBinaryPrefix);
                    case "kib":
                        return ConvertToBytes(Convert.ToDouble(value), 1, true);
                    case "mib":
                        return ConvertToBytes(Convert.ToDouble(value), 2, true);
                    case "gib":
                        return ConvertToBytes(Convert.ToDouble(value), 3, true);
                    default:
                        return (long)value;
                }
            }
            return 0;
        }

19 Source : QualityParser.cs
with GNU General Public License v3.0
from bonarr

public static QualityModel ParseQuality(string name)
        {
            Logger.Debug("Trying to parse quality for {0}", name);

            name = name.Trim();
            var normalizedName = name.Replace('_', ' ').Trim().ToLower();
            var result = ParseQualityModifiers(name, normalizedName);
            var subMatch = HardcodedSubsRegex.Matches(normalizedName).OfType<Match>().LastOrDefault();

            if (subMatch != null && subMatch.Success)
            {
                if (subMatch.Groups["hcsub"].Success)
                {
                    result.HardcodedSubs = subMatch.Groups["hcsub"].Value;
                }
                else if (subMatch.Groups["hc"].Success)
                {
                    result.HardcodedSubs = "Generic Hardcoded Subs";
                }
            }

            var sourceMatch = SourceRegex.Matches(normalizedName).OfType<Match>().LastOrDefault();
            var resolution = ParseResolution(normalizedName);
            var codecRegex = CodecRegex.Match(normalizedName);

            if (RemuxRegex.IsMatch(normalizedName))
            {
                if (resolution == Resolution.R2160p)
                {
                    result.Quality = Quality.Remux2160p;
                    return result;
                }

                if (resolution == Resolution.R1080p)
                {
                    result.Quality = Quality.Remux1080p;
                    return result;
                }
            }

            if (sourceMatch != null && sourceMatch.Success)
            {
                if (sourceMatch.Groups["bluray"].Success)
                {
                    if (codecRegex.Groups["xvid"].Success || codecRegex.Groups["divx"].Success)
                    {
                        result.Quality = Quality.DVD;
                        return result;
                    }

                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.Bluray2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.Bluray1080p;
                        return result;
                    }

                    if (resolution == Resolution.R576p)
                    {
                        result.Quality = Quality.Bluray576p;
                        return result;
                    }

                    if (resolution == Resolution.R480P)
                    {
                        result.Quality = Quality.Bluray480p;
                        return result;
                    }

                    result.Quality = Quality.Bluray720p;
                    return result;
                }

                if (sourceMatch.Groups["webdl"].Success)
                {
                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.WEBDL2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.WEBDL1080p;
                        return result;
                    }

                    if (resolution == Resolution.R720p)
                    {
                        result.Quality = Quality.WEBDL720p;
                        return result;
                    }

                    if (name.Contains("[WEBDL]"))
                    {
                        result.Quality = Quality.WEBDL720p;
                        return result;
                    }

                    result.Quality = Quality.WEBDL480p;
                    return result;
                }

                if (sourceMatch.Groups["hdtv"].Success)
                {
                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.HDTV2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.HDTV1080p;
                        return result;
                    }

                    if (resolution == Resolution.R720p)
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    if (name.Contains("[HDTV]"))
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    result.Quality = Quality.SDTV;
                    return result;
                }

                if (sourceMatch.Groups["bdrip"].Success ||
                    sourceMatch.Groups["brrip"].Success)
                {
                    if (codecRegex.Groups["xvid"].Success || codecRegex.Groups["divx"].Success)
                    {
                        result.Quality = Quality.DVD;
                        return result;
                    }
                    
                    switch (resolution)
                    {
                        case Resolution.R720p:
                            result.Quality = Quality.Bluray720p;
                            return result;
                        case Resolution.R1080p:
                            result.Quality = Quality.Bluray1080p;
                            return result;
						case Resolution.R576p:
							result.Quality = Quality.Bluray576p;
							return result;
						case Resolution.R480P:
							result.Quality = Quality.Bluray480p;
							return result;
                        default:
                            result.Quality = Quality.Bluray480p;
                            return result;
                    }
                }

                if (sourceMatch.Groups["wp"].Success)
                {
                    result.Quality = Quality.WORKPRINT;
                    return result;
                }

                if (sourceMatch.Groups["dvd"].Success)
                {
                    result.Quality = Quality.DVD;
                    return result;
                }

                if (sourceMatch.Groups["dvdr"].Success)
                {
                    result.Quality = Quality.DVDR;
                    return result;
                }

                if (sourceMatch.Groups["scr"].Success)
                {
                    result.Quality = Quality.DVDSCR;
                    return result;
                }

                if (sourceMatch.Groups["regional"].Success)
                {
                    result.Quality = Quality.REGIONAL;
                    return result;
                }

                if (sourceMatch.Groups["cam"].Success)
                {
                    result.Quality = Quality.CAM;
                    return result;
                }

                if (sourceMatch.Groups["ts"].Success)
                {
                    result.Quality = Quality.TELESYNC;
                    return result;
                }

                if (sourceMatch.Groups["tc"].Success)
                {
                    result.Quality = Quality.TELECINE;
                    return result;
                }

                if (sourceMatch.Groups["pdtv"].Success ||
                    sourceMatch.Groups["sdtv"].Success ||
                    sourceMatch.Groups["dsr"].Success ||
                    sourceMatch.Groups["tvrip"].Success)
                {
                    if (HighDefPdtvRegex.IsMatch(normalizedName))
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    result.Quality = Quality.SDTV;
                    return result;
                }
            }

           


            //Anime Bluray matching
            if (AnimeBlurayRegex.Match(normalizedName).Success)
            {
                if (resolution == Resolution.R480P || resolution == Resolution.R576p || normalizedName.Contains("480p"))
                {
                    result.Quality = Quality.DVD;
                    return result;
                }

                if (resolution == Resolution.R1080p || normalizedName.Contains("1080p"))
                {
                    result.Quality = Quality.Bluray1080p;
                    return result;
                }

                result.Quality = Quality.Bluray720p;
                return result;
            }

            if (resolution == Resolution.R2160p)
            {
                result.Quality = Quality.HDTV2160p;
                return result;
            }

            if (resolution == Resolution.R1080p)
            {
                result.Quality = Quality.HDTV1080p;
                return result;
            }

            if (resolution == Resolution.R720p)
            {
                result.Quality = Quality.HDTV720p;
                return result;
            }

            if (resolution == Resolution.R480P)
            {
                result.Quality = Quality.SDTV;
                return result;
            }

            if (codecRegex.Groups["x264"].Success)
            {
                result.Quality = Quality.SDTV;
                return result;
            }

            if (normalizedName.Contains("848x480"))
            {
                if (normalizedName.Contains("dvd"))
                {
                    result.Quality = Quality.DVD;
                }

                result.Quality = Quality.SDTV;
            }

            if (normalizedName.Contains("1280x720"))
            {
                if (normalizedName.Contains("bluray"))
                {
                    result.Quality = Quality.Bluray720p;
                }

                result.Quality = Quality.HDTV720p;
            }

            if (normalizedName.Contains("1920x1080"))
            {
                if (normalizedName.Contains("bluray"))
                {
                    result.Quality = Quality.Bluray1080p;
                }

                result.Quality = Quality.HDTV1080p;
            }

            if (normalizedName.Contains("bluray720p"))
            {
                result.Quality = Quality.Bluray720p;
            }

            if (normalizedName.Contains("bluray1080p"))
            {
                result.Quality = Quality.Bluray1080p;
            }

            var otherSourceMatch = OtherSourceMatch(normalizedName);

            if (otherSourceMatch != Quality.Unknown)
            {
                result.Quality = otherSourceMatch;
            }

            //Based on extension
            if (result.Quality == Quality.Unknown && !name.ContainsInvalidPathChars())
            {
                try
                {
                    result.Quality = MediaFileExtensions.GetQualityForExtension(Path.GetExtension(name));
                    result.QualitySource = QualitySource.Extension;
                }
                catch (ArgumentException)
                {
                    //Swallow exception for cases where string contains illegal
                    //path characters.
                }
            }

            return result;
        }

19 Source : QualityParser.cs
with GNU General Public License v3.0
from bonarr

private static QualityModel ParseQualityModifiers(string name, string normalizedName)
        {
            var result = new QualityModel { Quality = Quality.Unknown };

            if (ProperRegex.IsMatch(normalizedName))
            {
                result.Revision.Version = 2;
            }

            var versionRegexResult = VersionRegex.Match(normalizedName);

            if (versionRegexResult.Success)
            {
                result.Revision.Version = Convert.ToInt32(versionRegexResult.Groups["version"].Value);
            }

            //TODO: re-enable this when we have a reliable way to determine real
            //TODO: Only treat it as a real if it comes AFTER the season/epsiode number
            var realRegexResult = RealRegex.Matches(name);

            if (realRegexResult.Count > 0)
            {
                result.Revision.Real = realRegexResult.Count;
            }

            return result;
        }

19 Source : FormulaConverter.cs
with GNU Lesser General Public License v3.0
from bookfx

[Pure]
        public static string R1C1ToA1(int row, int col, string formula) =>
            Parser
                .Matches(formula)
                .Cast<Match>()
                .Map(match => GetPart(row, col, match))
                .Join();

19 Source : Language.cs
with MIT License
from BotBuilderCommunity

public static IEnumerable<string> WordBreak(string input)
        {
            foreach (Match match in WordBreaker.Matches(input))
            {
                yield return match.Value;
            }
        }

19 Source : Language.cs
with MIT License
from BotBuilderCommunity

public static string ANormalization(string input)
        {
            if (System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "en")
            {
                var builder = new StringBuilder();
                var last = 0;
                foreach (Match match in _aOrAn.Matches(input))
                {
                    var currentWord = match.Groups[1];
                    builder.Append(input.Substring(last, currentWord.Index - last));
                    if (match.Groups[2].Success)
                    {
                        builder.Append("an");
                    }
                    else
                    {
                        builder.Append("a");
                    }
                    last = currentWord.Index + currentWord.Length;
                }
                builder.Append(input.Substring(last));
                return builder.ToString();
            }
            else
            {
                return input;
            }
        }

19 Source : IPrompt.cs
with MIT License
from BotBuilderCommunity

public static bool ValidatePattern(IForm<T> form, string pattern, IField<T> field, int argLimit = 0)
        {
            bool ok = true;
            var fields = form.Fields;
            foreach (Match match in _args.Matches(pattern))
            {
                var expr = match.Groups[1].Value.Trim();
                int numeric;
                if (expr == "||")
                {
                    ok = true;
                }
                else if (expr.StartsWith("&"))
                {
                    var name = expr.Substring(1);
                    if (name == string.Empty && field != null) name = field.Name;
                    ok = (name == string.Empty || fields.Field(name) != null);
                }
                else if (expr.StartsWith("?"))
                {
                    ok = ValidatePattern(form, expr.Substring(1), field, argLimit);
                }
                else if (expr.StartsWith("["))
                {
                    if (expr.EndsWith("]"))
                    {
                        ok = ValidatePattern(form, expr.Substring(1, expr.Length - 2), field, argLimit);
                    }
                    else
                    {
                        ok = false;
                    }
                }
                else if (expr.StartsWith("*"))
                {
                    ok = (expr == "*" || expr == "*filled");
                }
                else if (TryParseFormat(expr, out numeric))
                {
                    ok = numeric <= argLimit - 1;
                }
                else
                {
                    var formatArgs = expr.Split(':');
                    var name = formatArgs[0];
                    if (name == string.Empty && field != null) name = field.Name;
                    ok = (name == string.Empty || fields.Field(name) != null);
                }
                if (!ok)
                {
                    break;
                }
            }
            return ok;
        }

19 Source : IPrompt.cs
with MIT License
from BotBuilderCommunity

private string ExpandTemplate(string template, string currentChoice, string noValue, T state, IField<T> field, object[] args, ref IList<DescribeAttribute> buttons)
        {
            bool foundUnspecified = false;
            int last = 0;
            int numeric;
            var response = new StringBuilder();

            foreach (Match match in _args.Matches(template))
            {
                var expr = match.Groups[1].Value.Trim();
                var subsreplacedute = string.Empty;
                if (expr.StartsWith("&"))
                {
                    var name = expr.Substring(1);
                    if (name == string.Empty && field != null) name = field.Name;
                    var pathField = _fields.Field(name);
                    subsreplacedute = Language.Normalize(pathField == null ? field.Name : pathField.FieldDescription.Description, _annotation.FieldCase);
                }
                else if (expr == "||")
                {
                    var builder = new StringBuilder();
                    var values = _recognizer.ValueDescriptions();
                    var useButtons = !field.AllowsMultiple
                        && (_annotation.ChoiceStyle == ChoiceStyleOptions.Auto
                            || _annotation.ChoiceStyle == ChoiceStyleOptions.Buttons
                            || _annotation.ChoiceStyle == ChoiceStyleOptions.Carousel);
                    if (values.Any() && _annotation.AllowDefault != BoolDefault.False && field.Optional)
                    {
                        values = values.Concat(new DescribeAttribute[] { new DescribeAttribute(Language.Normalize(noValue, _annotation.ChoiceCase)) });
                    }
                    string current = null;
                    if (_annotation.AllowDefault != BoolDefault.False)
                    {
                        if (!field.Optional)
                        {
                            if (!field.IsUnknown(state))
                            {
                                current = ExpandTemplate(currentChoice, null, noValue, state, field, args, ref buttons);
                            }
                        }
                        else
                        {
                            current = ExpandTemplate(currentChoice, null, noValue, state, field, args, ref buttons);
                        }
                    }
                    if (values.Any())
                    {
                        if (useButtons)
                        {
                            foreach (var value in values)
                            {
                                buttons.Add(value);
                            }
                        }
                        else
                        {
                            // Buttons do not support multiple selection so we fall back to text
                            if (((_annotation.ChoiceStyle == ChoiceStyleOptions.Auto || _annotation.ChoiceStyle == ChoiceStyleOptions.AutoText)
                                && values.Count() < 4)
                                || (_annotation.ChoiceStyle == ChoiceStyleOptions.Inline))
                            {
                                // Inline choices
                                if (_annotation.ChoiceParens == BoolDefault.True) builder.Append('(');
                                var choices = new List<string>();
                                var i = 1;
                                foreach (var value in values)
                                {
                                    choices.Add(string.Format(_annotation.ChoiceFormat, i, Language.Normalize(value.Description, _annotation.ChoiceCase)));
                                    ++i;
                                }
                                builder.Append(Language.BuildList(choices, _annotation.ChoiceSeparator, _annotation.ChoiceLastSeparator));
                                if (_annotation.ChoiceParens == BoolDefault.True) builder.Append(')');
                                if (current != null)
                                {
                                    builder.Append(" ");
                                    builder.Append(current);
                                }
                            }
                            else
                            {
                                // Separate line choices
                                if (current != null)
                                {
                                    builder.Append(current);
                                    builder.Append(" ");
                                }
                                var i = 1;
                                foreach (var value in values)
                                {
                                    builder.AppendLine();
                                    builder.Append("  ");
                                    if (!_annotation.AllowNumbers)
                                    {
                                        builder.Append("* ");
                                    }
                                    builder.AppendFormat(_annotation.ChoiceFormat, i, Language.Normalize(value.Description, _annotation.ChoiceCase));
                                    ++i;
                                }
                            }
                        }
                    }
                    else if (current != null)
                    {
                        builder.Append(" ");
                        builder.Append(current);
                    }
                    subsreplacedute = builder.ToString();
                }
                else if (expr.StartsWith("*"))
                {
                    // Status display of active results
                    var filled = expr.ToLower().Trim().EndsWith("filled");
                    var builder = new StringBuilder();
                    if (match.Index > 0)
                    {
                        builder.AppendLine();
                    }
                    foreach (var entry in (from step in _fields where (!filled || !step.IsUnknown(state)) && step.Role == FieldRole.Value && step.Active(state) select step))
                    {
                        var format = new Prompter<T>(Template(entry, TemplateUsage.StatusFormat), _form, null);
                        builder.Append("* ").AppendLine(format.Prompt(state, entry).Prompt);
                    }
                    subsreplacedute = builder.ToString();
                }
                else if (expr.StartsWith("[") && expr.EndsWith("]"))
                {
                    // Generate a list from multiple fields
                    var paths = expr.Substring(1, expr.Length - 2).Split(' ');
                    var values = new List<Tuple<IField<T>, object, string>>();
                    foreach (var spec in paths)
                    {
                        if (!spec.StartsWith("{") || !spec.EndsWith("}"))
                        {
                            throw new ArgumentException("Only {<field>} references are allowed in lists.");
                        }
                        var formatArgs = spec.Substring(1, spec.Length - 2).Trim().Split(':');
                        var name = formatArgs[0];
                        if (name == string.Empty && field != null) name = field.Name;
                        var format = (formatArgs.Length > 1 ? "0:" + formatArgs[1] : "0");
                        var eltDesc = _fields.Field(name);
                        if (!eltDesc.IsUnknown(state))
                        {
                            var value = eltDesc.GetValue(state);
                            if (value.GetType() != typeof(string) && value.GetType().IsIEnumerable())
                            {
                                var eltValues = (value as System.Collections.IEnumerable);
                                foreach (var elt in eltValues)
                                {
                                    values.Add(Tuple.Create(eltDesc, elt, format));
                                }
                            }
                            else
                            {
                                values.Add(Tuple.Create(eltDesc, eltDesc.GetValue(state), format));
                            }
                        }
                    }
                    if (values.Count() > 0)
                    {
                        var elements = (from elt in values
                                        select Language.Normalize(ValueDescription(elt.Item1, elt.Item2, elt.Item3), _annotation.ValueCase)).ToArray();
                        subsreplacedute = Language.BuildList(elements, _annotation.Separator, _annotation.LastSeparator);
                    }
                }
                else if (expr.StartsWith("?"))
                {
                    // Conditional template
                    var subValue = ExpandTemplate(expr.Substring(1), currentChoice, null, state, field, args, ref buttons);
                    if (subValue == null)
                    {
                        subsreplacedute = string.Empty;
                    }
                    else
                    {
                        subsreplacedute = subValue;
                    }
                }
                else if (TryParseFormat(expr, out numeric))
                {
                    // Process ad hoc arg
                    if (numeric < args.Length && args[numeric] != null)
                    {
                        subsreplacedute = string.Format("{" + expr + "}", args);
                    }
                    else
                    {
                        foundUnspecified = true;
                        break;
                    }
                }
                else
                {
                    var formatArgs = expr.Split(':');
                    var name = formatArgs[0];
                    if (name == string.Empty && field != null) name = field.Name;
                    var pathDesc = _fields.Field(name);
                    if (pathDesc.IsUnknown(state))
                    {
                        if (noValue == null)
                        {
                            foundUnspecified = true;
                            break;
                        }
                        subsreplacedute = noValue;
                    }
                    else
                    {
                        var value = pathDesc.GetValue(state);
                        if (value.GetType() != typeof(string) && value.GetType().IsIEnumerable())
                        {
                            if (value.GetType().IsAttachmentCollection())
                            {
                                var locTemplate = this._form.Configuration.Template(TemplateUsage.AttachmentCollectionDescription);
                                subsreplacedute = string.Format(locTemplate.Pattern(), (value as IEnumerable<AwaitableAttachment>).Count());
                            }
                            else
                            {
                                var values = (value as System.Collections.IEnumerable);
                                subsreplacedute = Language.BuildList(from elt in values.Cast<object>()
                                                                select Language.Normalize(ValueDescription(pathDesc, elt, "0"), _annotation.ValueCase),
                                    _annotation.Separator, _annotation.LastSeparator);
                            }
                        }
                        else if (value.GetType().IsAttachmentType())
                        {
                            var attachment = (value as AwaitableAttachment).Attachment;
                            var locTemplate = this._form.Configuration.Template(TemplateUsage.AttachmentFieldDescription);
                            subsreplacedute = string.Format(locTemplate.Pattern(), attachment.Name, attachment.ContentType);
                        }
                        else
                        {
                            var format = (formatArgs.Length > 1 ? "0:" + formatArgs[1] : "0");
                            subsreplacedute = ValueDescription(pathDesc, value, format);
                        }
                    }
                }
                response.Append(template.Substring(last, match.Index - last)).Append(subsreplacedute);
                last = match.Index + match.Length;
            }
            return (foundUnspecified ? null : response.Append(template.Substring(last, template.Length - last)).ToString());
        }

19 Source : Worker.cs
with MIT License
from botman99

private bool ScanFileForMatches(string Filename)  // scan through the specified file to look for search text matches
		{
			Regex regex = null;

			if( Globals.bRegEx )
			{
				regex = new Regex(Globals.SearchString, Globals.bCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);
			}

			StreamReader sr = null;

			try
			{
				sr = new StreamReader(Filename,true);
			}
			catch( Exception e )
			{
				Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
				return false;
			}

			bool bFoundMatchInFile = false;
			int LineNumber = 0;
			int NumberOfMatchesInFile = 0;

			string[] PreviewLines = new string[5];  // circular buffer of preview lines (for displaying before and after matches)
			int PreviewLineIndex = -1;  // we haven't added a line to the circular buffer yet
			int PreviewLineCount = 0;  // number of lines in the preview circular buffer that are valid

			int LinesSinceMatch = -1;  // reset this to 0 when we find a match so we know when to store "after" preview lines following a match

			string line = "";

			while (!Globals.bShouldStopWorkerJobs && (sr.Peek() >= 0))
			{
				line = ReadLine(sr);

				LineNumber++;

				ReadLineSleepCount++;
				if( ReadLineSleepCount >= 1000 )
				{
					ReadLineSleepCount = 0;
					Thread.Sleep(0);  // force context switch
				}

				int MatchesInLine = 0;

				if( Globals.bRegEx && (regex != null) )
				{
					MatchCollection matches = regex.Matches(line);
					MatchesInLine = matches.Count;

					if( matches.Count > 0 )
					{
						List<MatchPos> Matches = new List<MatchPos>();

						for( int i = 0; i < matches.Count; i++ )
						{
							MatchPos Match = new MatchPos(matches[i].Index, matches[i].Length);
							Matches.Add(Match);
						}

						AddMatchLine(ref line, ref Matches, ref PreviewLines, ref PreviewLineIndex, ref PreviewLineCount, ref LineNumber, ref LinesSinceMatch);
					}
				}
				else
				{
					int pos = line.IndexOf(Globals.SearchString, 0, Globals.bCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);

					if( pos >= 0 )
					{
						List<MatchPos> Matches = new List<MatchPos>();

						while( pos >= 0 )
						{
							if( Globals.bShouldStopWorkerJobs )
							{
								sr.Close();
								return false;
							}

							MatchesInLine++;

							MatchPos Match = new MatchPos(pos, Globals.SearchString.Length);
							Matches.Add(Match);

							if( pos < (line.Length - 1) )
							{
								pos = line.IndexOf(Globals.SearchString, pos+1, Globals.bCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
							}
							else
							{
								pos = -1;
							}
						}

						AddMatchLine(ref line, ref Matches, ref PreviewLines, ref PreviewLineIndex, ref PreviewLineCount, ref LineNumber, ref LinesSinceMatch);
					}
				}

				if( MatchesInLine > 0 )
				{
					bFoundMatchInFile = true;
				}
				else  // if no matches, add this line to the circular preview buffer
				{
					PreviewLineIndex = (PreviewLineIndex + 1) % 5;
					PreviewLines[PreviewLineIndex] = line;

					PreviewLineCount = Math.Min(PreviewLineCount + 1, 5);

					if( LinesSinceMatch >= 0 )
					{
						LinesSinceMatch++;

						try
						{
							if( (LinesSinceMatch == 5) || (sr.Peek() == -1) )  // if we're read 5 lines or reached the end of the file...
							{
								int PreviewIndex = PreviewLineIndex - (PreviewLineCount - 1);  // index in the circular buffer of the oldest preview line
								if( PreviewIndex < 0 )
								{
									PreviewIndex += 5;
								}

								for( int index = 0; index < PreviewLineCount; index++ )
								{
									Globals.SearchLine PreviewSearchLine = new Globals.SearchLine();

									PreviewSearchLine.LineNumber = LineNumber - (PreviewLineCount - index) + 1;
									PreviewSearchLine.Line = PreviewLines[PreviewIndex++];
									if( PreviewIndex == 5 )
									{
										PreviewIndex = 0;
									}
									PreviewSearchLine.bIsSearchTextMatch = false;

									Globals.SearchFiles[SearchFilesIndex].Lines.Add(PreviewSearchLine);
								}

								PreviewLineIndex = -1;  // reset the circular buffer
								PreviewLineCount = 0;

								LinesSinceMatch = -1;
							}
						}
						catch( Exception e )
						{
							Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
						}
					}
				}

				NumberOfMatchesInFile += MatchesInLine;
			}

			try
			{
				sr.Close();
			}
			catch( Exception e )
			{
				Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
			}

			if (Globals.bShouldStopWorkerJobs)
			{
				return false;
			}

			Globals.SearchFiles[SearchFilesIndex].SearchMatchCount = NumberOfMatchesInFile;

			return bFoundMatchInFile;
		}

19 Source : ObjectSerializer.cs
with MIT License
from brian91292

public void Load(object obj, string path)
        {
            if (ConvertFromString.Count == 0)
                InitTypeHandlers();

            string backupPath = path + ".bak";
            if (File.Exists(backupPath) && !File.Exists(path))
            {
                File.Move(backupPath, path);
            }

            if (File.Exists(path))
            {
                var matches = _configRegex.Matches(File.ReadAllText(path));
                string currentSection = null;
                foreach (Match match in matches)
                {
                    if (match.Groups["Section"].Success)
                    {
                        currentSection = match.Groups["Section"].Value;
                        continue;
                    }

                    // Grab the name, which has to exist or the regex wouldn't have matched
                    var name = match.Groups["Name"].Value;

                    // Check if any comments existed
                    if (match.Groups["Comment"].Success)
                    {
                        // Then store them in memory so we can write them back later on
                        _comments[name] = match.Groups["Comment"].Value.TrimEnd(new char[] { '\n', '\r' });
                    }

                    // If there's no value, continue on at this point
                    if (!match.Groups["Value"].Success)
                        continue;
                    var value = match.Groups["Value"].Value;

                    // Otherwise, read the value in with the appropriate handler
                    var fieldInfo = obj.GetType().GetField(name.Replace(".", "_"));

                    if (fieldInfo == null)
                    {
                        // Skip missing fields, incase one was changed or removed.
                        continue;
                    }

                    // If the fieldType is an enum, replace it with the generic Enum type
                    Type fieldType = fieldInfo.FieldType.IsEnum ? typeof(Enum) : fieldInfo.FieldType;

                    // Invoke our ConvertFromString method if it exists
                    if (!ConvertFromString.TryGetValue(fieldType, out var convertFromString))
                    {
                        if (CreateDynamicFieldConverter(fieldInfo))
                        {
                            convertFromString = ConvertFromString[fieldType];
                        }
                    }
                    try
                    {
                        object converted = convertFromString.Invoke(fieldInfo, value);
                        fieldInfo.SetValue(obj, converted);
                    }
                    catch (Exception ex)
                    {
                        //Plugin.Log($"Failed to parse field {name} with value {value} as type {fieldInfo.FieldType.Name}. {ex.ToString()}");
                    }
                }
            }
        }

19 Source : TwitchMessageParser.cs
with MIT License
from brian91292

public bool ParseRawMessage(string rawMessage, ConcurrentDictionary<string, IChatChannel> channelInfo, IChatUser loggedInUser, out IChatMessage[] parsedMessages)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            parsedMessages = null;
            var matches = _twitchMessageRegex.Matches(rawMessage);
            if (matches.Count == 0)
            {
                _logger.LogInformation($"Unhandled message: {rawMessage}");
                stopwatch.Stop();
                return false;
            }

            List<IChatMessage> messages = new List<IChatMessage>();
            //_logger.LogInformation($"Parsing message {rawMessage}");
            foreach (Match match in matches)
            {
                if (!match.Groups["MessageType"].Success)
                {
                    _logger.LogInformation($"Failed to get messageType for message {match.Value}");
                    continue;
                }

                //_logger.LogInformation($"Message: {match.Value}");

                string messageType = match.Groups["MessageType"].Value;
                string messageText = match.Groups["Message"].Success ? match.Groups["Message"].Value : "";
                string messageChannelName = match.Groups["ChannelName"].Success ? match.Groups["ChannelName"].Value.Trim(new char[] { '#' }) : "";
                string messageRoomId = "";

                if (channelInfo.TryGetValue(messageChannelName, out var channel))
                {
                    messageRoomId = channel.AsTwitchChannel().Roomstate?.RoomId;
                }

                try
                {
                    IChatBadge[] userBadges = new IChatBadge[0];
                    List<IChatEmote> messageEmotes = new List<IChatEmote>();
                    TwitchRoomstate messageRoomstate = null;
                    HashSet<string> foundTwitchEmotes = new HashSet<string>();

                    bool isActionMessage = false, isHighlighted = false;
                    if (messageText.StartsWith("\u0001ACTION"))
                    {
                        messageText = messageText.Remove(messageText.Length - 1, 1).Remove(0, 8);
                        isActionMessage = true;
                    }

                    var messageMeta = new ReadOnlyDictionary<string, string>(_tagRegex.Matches(match.Value).Cast<Match>().Aggregate(new Dictionary<string, string>(), (dict, m) =>
                    {
                        dict[m.Groups["Tag"].Value] = m.Groups["Value"].Value;
                        return dict;
                    }));

                    int messageBits = messageMeta.TryGetValue("bits", out var bitsString) && int.TryParse(bitsString, out var bitsInt) ? bitsInt : 0;

                    if (messageMeta.TryGetValue("badges", out var badgeStr))
                    {
                        userBadges = badgeStr.Split(',').Aggregate(new List<IChatBadge>(), (list, m) =>
                        {
                            var badgeId = m.Replace("/", "");
                            if (_twitchDataProvider.TryGetBadgeInfo(badgeId, messageRoomId, out var badgeInfo))
                            {
                                list.Add(new TwitchBadge()
                                {
                                    Id = $"{badgeInfo.Type}_{badgeId}",
                                    Name = m.Split('/')[0],
                                    Uri = badgeInfo.Uri
                                });
                            }
                            return list;
                        }).ToArray();
                    }

                    if (messageType == "PRIVMSG" || messageType == "NOTIFY" || messageType == "USERNOTICE")
                    {
                        if (messageText.Length > 0)
                        {
                            if (_settings.ParseTwitchEmotes && messageMeta.TryGetValue("emotes", out var emoteStr))
                            {
                                // Parse all the normal Twitch emotes
                                messageEmotes = emoteStr.Split('/').Aggregate(new List<IChatEmote>(), (emoteList, emoteInstanceString) =>
                                {
                                    var emoteParts = emoteInstanceString.Split(':');
                                    foreach (var instanceString in emoteParts[1].Split(','))
                                    {
                                        var instanceParts = instanceString.Split('-');
                                        int startIndex = int.Parse(instanceParts[0]);
                                        int endIndex = int.Parse(instanceParts[1]);

                                        if (startIndex >= messageText.Length)
                                        {
                                            _logger.LogWarning($"Start index is greater than message length! RawMessage: {match.Value}, InstanceString: {instanceString}, EmoteStr: {emoteStr}, StartIndex: {startIndex}, MessageLength: {messageText.Length}, IsActionMessage: {isActionMessage}");
                                        }
                                        string emoteName = messageText.Substring(startIndex, endIndex - startIndex + 1);
                                        foundTwitchEmotes.Add(emoteName);
                                        emoteList.Add(new TwitchEmote()
                                        {
                                            Id = $"TwitchEmote_{emoteParts[0]}",
                                            Name = emoteName,//endIndex >= messageText.Length ? messageText.Substring(startIndex) : ,
                                            Uri = $"https://static-cdn.jtvnw.net/emoticons/v1/{emoteParts[0]}/3.0",
                                            StartIndex = startIndex,
                                            EndIndex = endIndex,
                                            IsAnimated = false,
                                            Bits = 0,
                                            Color = ""
                                        });
                                    }
                                    return emoteList;
                                });
                            }

                            // Parse all the third party (BTTV, FFZ, etc) emotes
                            StringBuilder currentWord = new StringBuilder();
                            for (int i = 0; i <= messageText.Length; i++)
                            {
                                if (i == messageText.Length || char.IsWhiteSpace(messageText[i]))
                                {
                                    if (currentWord.Length > 0)
                                    {
                                        var lastWord = currentWord.ToString();
                                        int startIndex = i - lastWord.Length;
                                        int endIndex = i - 1;

                                        if (!foundTwitchEmotes.Contains(lastWord))
                                        {
                                            // Make sure we haven't already matched a Twitch emote with the same string, just incase the user has a BTTV/FFZ emote with the same name
                                            if (_settings.ParseCheermotes && messageBits > 0 && _twitchDataProvider.TryGetCheermote(lastWord, messageRoomId, out var cheermoteData, out var numBits) && numBits > 0)
                                            {
                                                //_logger.LogInformation($"Got cheermote! Total message bits: {messageBits}");
                                                var tier = cheermoteData.GetTier(numBits);
                                                if (tier != null)
                                                {
                                                    messageEmotes.Add(new TwitchEmote()
                                                    {
                                                        Id = $"TwitchCheermote_{cheermoteData.Prefix}{tier.MinBits}",
                                                        Name = lastWord,
                                                        Uri = tier.Uri,
                                                        StartIndex = startIndex,
                                                        EndIndex = endIndex,
                                                        IsAnimated = true,
                                                        Bits = numBits,
                                                        Color = tier.Color
                                                    });
                                                }
                                            }
                                            else if (_twitchDataProvider.TryGetThirdPartyEmote(lastWord, messageChannelName, out var emoteData))
                                            {
                                                if (emoteData.Type.StartsWith("BTTV") && _settings.ParseBTTVEmotes || emoteData.Type.StartsWith("FFZ") && _settings.ParseFFZEmotes)
                                                {
                                                    messageEmotes.Add(new TwitchEmote()
                                                    {
                                                        Id = $"{emoteData.Type}_{lastWord}",
                                                        Name = lastWord,
                                                        Uri = emoteData.Uri,
                                                        StartIndex = startIndex,
                                                        EndIndex = endIndex,
                                                        IsAnimated = emoteData.IsAnimated,
                                                        Bits = 0,
                                                        Color = ""
                                                    });
                                                }
                                            }
                                        }
                                        currentWord.Clear();
                                    }
                                }
                                else
                                {
                                    currentWord.Append(messageText[i]);
                                }
                            }

                            if (_settings.ParseEmojis)
                            {
                                // Parse all emojis
                                messageEmotes.AddRange(_emojiParser.FindEmojis(messageText));
                            }

                            // Sort the emotes in descending order to make replacing them in the string later on easier
                            messageEmotes.Sort((a, b) =>
                            {
                                return b.StartIndex - a.StartIndex;
                            });
                        }
                    }
                    else if (messageType == "ROOMSTATE")
                    {
                        messageRoomstate = new TwitchRoomstate()
                        {
                            BroadcasterLang = messageMeta.TryGetValue("broadcaster-lang", out var lang) ? lang : "",
                            RoomId = messageMeta.TryGetValue("room-id", out var roomId) ? roomId : "",
                            EmoteOnly = messageMeta.TryGetValue("emote-only", out var emoteOnly) ? emoteOnly == "1" : false,
                            FollowersOnly = messageMeta.TryGetValue("followers-only", out var followersOnly) ? followersOnly != "-1" : false,
                            MinFollowTime = followersOnly != "-1" && int.TryParse(followersOnly, out var minFollowTime) ? minFollowTime : 0,
                            R9K = messageMeta.TryGetValue("r9k", out var r9k) ? r9k == "1" : false,
                            SlowModeInterval = messageMeta.TryGetValue("slow", out var slow) && int.TryParse(slow, out var slowModeInterval) ? slowModeInterval : 0,
                            SubscribersOnly = messageMeta.TryGetValue("subs-only", out var subsOnly) ? subsOnly == "1" : false
                        };
                        if (channel is TwitchChannel twitchChannel)
                        {
                            twitchChannel.Roomstate = messageRoomstate;
                        }
                    }

                    string userName = match.Groups["HostName"].Success ? match.Groups["HostName"].Value.Split('!')[0] : "";
                    string displayName = messageMeta.TryGetValue("display-name", out var name) ? name : userName;
                    var newMessage = new TwitchMessage()
                    {
                        Id = messageMeta.TryGetValue("id", out var messageId) ? messageId : "", // TODO: default id of some sort?
                        Sender = new TwitchUser()
                        {
                            Id = messageMeta.TryGetValue("user-id", out var uid) ? uid : "",
                            UserName = userName,
                            DisplayName = displayName,
                            Color = messageMeta.TryGetValue("color", out var color) ? color : ChatUtils.GetNameColor(userName),
                            IsModerator = badgeStr != null && badgeStr.Contains("moderator/"),
                            IsBroadcaster = badgeStr != null && badgeStr.Contains("broadcaster/"),
                            IsSubscriber = badgeStr != null && (badgeStr.Contains("subscriber/") || badgeStr.Contains("founder/")),
                            IsTurbo = badgeStr != null && badgeStr.Contains("turbo/"),
                            IsVip = badgeStr != null && badgeStr.Contains("vip/"),
                            Badges = userBadges
                        },
                        Channel = channel != null ? channel : new TwitchChannel()
                        {
                            Id = messageChannelName,
                            Name = messageChannelName,
                            Roomstate = messageRoomstate
                        },
                        Emotes = messageEmotes.ToArray(),
                        Message = messageText,
                        IsActionMessage = isActionMessage,
                        IsSystemMessage = messageType == "NOTICE" || messageType == "USERNOTICE",
                        IsHighlighted = isHighlighted,
                        IsPing = !string.IsNullOrEmpty(messageText) && loggedInUser != null && messageText.Contains($"@{loggedInUser.DisplayName}", StringComparison.OrdinalIgnoreCase),
                        Bits = messageBits,
                        Metadata = messageMeta,
                        Type = messageType
                    };

                    if(messageMeta.TryGetValue("msg-id", out var msgIdValue))
                    {
                        TwitchMessage systemMessage = null;
                        //_logger.LogInformation($"msg-id: {msgIdValue}");
                        //_logger.LogInformation($"Message: {match.Value}");
                        switch(msgIdValue)
                        {
                            case "skip-subs-mode-message":
                                systemMessage = (TwitchMessage)newMessage.Clone();
                                systemMessage.Message = "Redeemed Send a Message In Sub-Only Mode";
                                systemMessage.IsHighlighted = false;
                                systemMessage.IsSystemMessage = true;
                                systemMessage.Emotes = new IChatEmote[0];
                                messages.Add(systemMessage);
                                break;
                            case "highlighted-message":
                                systemMessage = (TwitchMessage)newMessage.Clone();
                                systemMessage.Message = "Redeemed Highlight My Message";
                                systemMessage.IsHighlighted = true;
                                systemMessage.IsSystemMessage = true;
                                systemMessage.Emotes = new IChatEmote[0];
                                messages.Add(systemMessage);
                                break;
                            //case "sub":
                            //case "resub":
                            //case "raid":
                            default:
                                _logger.LogInformation($"Message: {match.Value}");
                                if (messageMeta.TryGetValue("system-msg", out var systemMsgText))
                                {
                                    systemMessage = (TwitchMessage)newMessage.Clone();
                                    systemMsgText = systemMsgText.Replace(@"\s", " ");
                                    systemMessage.IsHighlighted = true;
                                    systemMessage.IsSystemMessage = true;

                                    //_logger.LogInformation($"Message: {match.Value}");
                                    if (messageMeta.TryGetValue("msg-param-sub-plan", out var subPlanName))
                                    {
                                        if (subPlanName == "Prime")
                                        {
                                            systemMessage.Message = $"👑  {systemMsgText}";
                                        }
                                        else
                                        {
                                            systemMessage.Message = $"⭐  {systemMsgText}";
                                        }
                                        systemMessage.Emotes = _emojiParser.FindEmojis(systemMessage.Message).ToArray();
                                    }
                                    else if (messageMeta.TryGetValue("msg-param-profileImageURL", out var profileImage) && messageMeta.TryGetValue("msg-param-login", out var loginUser))
                                    {
                                        var emoteId = $"ProfileImage_{loginUser}";
                                        systemMessage.Emotes = new IChatEmote[]
                                        {
                                            new TwitchEmote()
                                            {
                                                Id = emoteId,
                                                Name = $"[{emoteId}]",
                                                Uri = profileImage,
                                                StartIndex = 0,
                                                EndIndex = emoteId.Length + 1,
                                                IsAnimated = false,
                                                Bits = 0,
                                                Color = ""
                                            }
                                        };
                                        systemMessage.Message = $"{systemMessage.Emotes[0].Name}  {systemMsgText}";
                                    }
                                    messages.Add(systemMessage);
                                }
                                else
                                {
                                    // If there's no system message, the message must be the actual message.
                                    // In this case we wipe out the original message and skip it.
                                    systemMessage = (TwitchMessage)newMessage.Clone();
                                    systemMessage.IsHighlighted = true;
                                    systemMessage.IsSystemMessage = true;
                                    newMessage.Message = "";
                                    messages.Add(systemMessage);
                                }
                                newMessage.IsSystemMessage = false;
                                if (string.IsNullOrEmpty(newMessage.Message))
                                {
                                    // If there was no actual message, then we only need to queue up the system message
                                    continue;
                                }
                                break;
                        }
                    }

                    //_logger.LogInformation($"RawMsg: {rawMessage}");
                    //foreach(var kvp in newMessage.Metadata)
                    //{
                    //    _logger.LogInformation($"Tag: {kvp.Key}, Value: {kvp.Value}");
                    //}
                    messages.Add(newMessage);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Exception while parsing Twitch message {messageText}");
                }
            }
            if (messages.Count > 0)
            {
                stopwatch.Stop();
                _logger.LogDebug($"Successfully parsed {messages.Count} messages in {(decimal)stopwatch.ElapsedTicks/TimeSpan.TicksPerMillisecond}ms");
                parsedMessages = messages.ToArray();
                return true;
            }
            _logger.LogInformation("No messages were parsed successfully.");
            return false;
        }

19 Source : FrwTwemojiParser.cs
with MIT License
from brian91292

public List<IChatEmote> FindEmojis(string str)
        {
            List<IChatEmote> emojis = new List<IChatEmote>();
            if (string.IsNullOrEmpty(str))
            {
                return emojis;
            }

            //_logger.LogInformation($"Message: {str}, Bytes: {BitConverter.ToString(Encoding.UTF32.GetBytes(str))}");

            foreach(Match match in _emojiRegex.Matches(str))
            {
                //_logger.LogInformation($"Match: {match.Value}, Bytes: {BitConverter.ToString(Encoding.UTF32.GetBytes(match.Value))}, Index: {match.Index}, Length: {match.Length}");

                string unicodeStr = WebParseEmojiRegExMatchEvaluator(match);

                if (string.IsNullOrEmpty(unicodeStr))
                {
                    continue;
                }
                var emoji = new Emoji()
                {
                    Id = $"Emoji_{unicodeStr}",
                    Name = match.Value,
                    StartIndex = match.Index,
                    EndIndex = match.Index + match.Length-1,
                    Uri = $"https://raw.githubusercontent.com/twitter/twemoji/32958b019cfb451575389851a5979f31a2a14d08/replacedets/72x72/{unicodeStr.ToLower()}.png",
                    IsAnimated = false
                };
                //_logger.LogInformation($"Match: {BitConverter.ToString(Encoding.UTF32.GetBytes(match.Value))}, Emoji: {unicodeStr}, StartIndex: {emoji.StartIndex}, EndIndex: {emoji.EndIndex}, Uri: {emoji.Uri}");
                emojis.Add(emoji);
            }
            return emojis;
        }

19 Source : StringExtensions.cs
with MIT License
from CacoCode

[Description("获取全部手机号")]
        public static List<string> GetPhoneNumbers(this string str, string pattern = RegexConst.PhoneNumber)
        {
            var reg = new Regex(pattern);
            var matches = reg.Matches(str);
            return (from Match item in matches select item.Value).ToList();
        }

19 Source : StringExtensions.cs
with MIT License
from CacoCode

[Description("正则匹配多个")]
        public static List<string> RegexMatches(this string str, string pattern)
        {
            var reg = new Regex(pattern);
            var matches = reg.Matches(str);
            return (from Match item in matches select item.Value).ToList();
        }

19 Source : FirstBootMenu.cs
with GNU General Public License v2.0
from Caeden117

private string GuessSteamInstallationDirectoryComplex()
    {
        // The above registry key only exists if you've installed Beat Saber since last installing windows
        // if you copy the game files or reinstall windows then the registry key will be missing even though
        // the game launches just fine
        var steamRegistryKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Valve\\Steam";
        var registryValue = "InstallPath";

        var libraryFolders = new List<string>();

        var mainSteamFolder = (string)Registry.GetValue(steamRegistryKey, registryValue, "");
        libraryFolders.Add(mainSteamFolder);

        var libraryFolderFilename = mainSteamFolder + "\\steamapps\\libraryfolders.vdf";
        if (File.Exists(libraryFolderFilename))
        {
            using (var reader = new StreamReader(libraryFolderFilename))
            {
                var text = reader.ReadToEnd();
                var matches = libraryRegex.Matches(text);

                foreach (Match match in matches)
                {
                    if (Directory.Exists(match.Groups[1].Value))
                        libraryFolders.Add(match.Groups[1].Value);
                }
            }
        }

        foreach (var libraryFolder in libraryFolders)
        {
            var fileName = libraryFolder + "\\steamapps\\appmanifest_620980.acf";
            if (File.Exists(fileName))
            {
                using (var reader = new StreamReader(fileName))
                {
                    var text = reader.ReadToEnd();

                    var installDirMatch = appManifestRegex.Matches(text)[0].Groups;
                    var installDir = libraryFolder + "\\steamapps\\common\\" + installDirMatch[1].Value;

                    if (Directory.Exists(installDir)) return installDir;
                }
            }
        }

        return "";
    }

19 Source : Extensions.cs
with Apache License 2.0
from Capnode

public static string WithEmbeddedHtmlAnchors(this string source)
        {
            var regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
            var matches = regx.Matches(source);
            foreach (Match match in matches)
            {
                source = source.Replace(match.Value, $"<a href=\'{match.Value}\' target=\'blank\'>{match.Value}</a>");
            }
            return source;
        }

19 Source : Utility.cs
with Apache License 2.0
from casbin

public static string Escapereplacedertion(string s)
        {
            // 替换第一个点
            if (s.StartsWith(PermConstants.DefaultRequestType) || s.StartsWith(PermConstants.DefaultPolicyType))
            {
                s = s.ReplaceFirst(@".", "_");
            }
            const string regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\.";
            var p = new Regex(regex);
            var matches = p.Matches(s);
            var sb = new StringBuilder(s);

            for (int i = 0, j = matches.Count; i < j; i++)
            {
                var match = matches[i];
                string replace = match.Groups[0].Value.Replace(".", "_");
                if (replace.Trim().Length > 0)
                {
                    sb.Replace(match.Value, replace, match.Index, match.Length);
                }
            }
            return sb.ToString();
        }

19 Source : Utility.cs
with Apache License 2.0
from casbin

internal static bool TryGetEvalRuleNames(string expressString, out IEnumerable<string> evalRuleNames)
        {
            MatchCollection matches = s_evalRegex.Matches(expressString);
            int matchCount = matches.Count;
            if (matchCount is 0)
            {
                evalRuleNames = null;
                return false;
            }
            string[] rules = new string[matchCount];
            for (int i = 0; i < matchCount; i++)
            {
                GroupCollection group = matches[i].Groups;
                if (group.Count < 2)
                {
                    evalRuleNames = null;
                    return false;
                }
                rules[i] = group[1].Value;
            }
            evalRuleNames = rules;
            return true;
        }

19 Source : RouteCompiler.cs
with MIT License
from CatLib

private static string[] MatchParameters(string uri, string regstr, ref int[] parameIndex)
        {
            var reg = new Regex(regstr);
            var mc = reg.Matches(uri);

            var parameters = new string[mc.Count];
            parameIndex = new int[mc.Count];
            for (var i = 0; i < mc.Count; i++)
            {
                parameIndex[i] = mc[i].Index;
                parameters[i] = mc[i].Groups[1].ToString();
            }

            return parameters;
        }

19 Source : Selector.cs
with MIT License
from CatLib

private string RangeExtract(string parts, int number)
        {
            var mc = extractReg.Matches(parts);

            if (mc.Count < 1)
            {
                return null;
            }
            if (mc[0].Groups.Count != 3)
            {
                return null;
            }

            var condition = mc[0].Groups[1].ToString();
            var val = mc[0].Groups[2].ToString();

            if (condition.Contains(","))
            {
                var fromTo = condition.Split(',');

                if (fromTo[0] == "*" && fromTo[1] == "*")
                {
                    return val;
                }

                if (fromTo[1] == "*" && number >= int.Parse(fromTo[0]))
                {
                    return val;
                }

                if (fromTo[0] == "*" && number <= int.Parse(fromTo[1]))
                {
                    return val;
                }

                if (fromTo[0] != "*" &&
                    fromTo[1] != "*" &&
                    number >= int.Parse(fromTo[0]) &&
                    number <= int.Parse(fromTo[1]))
                {
                    return val;
                }
            }

            return (condition == "*" || condition == number.ToString()) ? val : null;
        }

See More Examples