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

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

622 Examples 7

19 View Source File : EnvironmentVariableReader.cs
License : MIT License
Project Creator : 1100100

public static T Get<T>(string variable, T defaultValue = default)
        {
            var value = Environment.GetEnvironmentVariable(variable);
            if (string.IsNullOrWhiteSpace(value))
                return defaultValue;

            value = value.ReplaceIpPlaceholder();

            var matches = Regex.Matches(value, "[{](.*?)[}]");
            if (matches.Count > 0)
            {
                foreach (var match in matches)
                {
                    value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
                }
            }
            return (T)Convert.ChangeType(value, typeof(T));
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ReplaceVariable(Dictionary<string, string> variables, string text)
        {
            var matches = Regex.Matches(text, @"\${(?<key>.*?)}");
            foreach (Match item in matches)
            {
                var key = item.Groups["key"].Value;
                if (variables.ContainsKey(key))
                {
                    var value = variables[key];
                    text = text.Replace("${" + key + "}", value);
                }
            }
            return Regex.Replace(text, @"\s+", " ").Trim(' ');
        }

19 View Source File : EntityDescriptor.cs
License : MIT License
Project Creator : 17MKH

private void SetTableName()
    {
        var tableArr = EnreplacedyType.GetCustomAttribute<TableAttribute>(false);
        if (tableArr != null && tableArr.Name.NotNull())
        {
            TableName = tableArr.Name;
        }
        else
        {
            //去掉Enreplacedy后缀
            TableName = Name;

            //给表名称添加分隔符
            if (DbContext.Options.TableNameSeparator.NotNull())
            {
                var matchs = Regex.Matches(TableName, "[A-Z][^A-Z]+");
                TableName = string.Join(DbContext.Options.TableNameSeparator, matchs);
            }
        }

        var setPrefix = tableArr?.SetPrefix ?? true;
        //设置前缀
        if (setPrefix && DbContext.Options.TableNamePrefix.NotNull())
        {
            TableName = DbContext.Options.TableNamePrefix + TableName;
        }

        //设置自动创建表
        AutoCreate = tableArr?.AutoCreate ?? true;

        //表名称小写
        if (DbContext.Adapter.SqlLowerCase)
        {
            TableName = TableName.ToLower();
        }
    }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private string Handle_Payload()
        {
            //对用户输入的payload进行一些转换处理,方便下一步的加密
            string raw_input = textBox1.Text.Trim().Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); //支持多种linux win换行符
            string payload_pattern_csharp = @"\{(.+?)\}";
            string payload_pattern_c = @"=.*"";$";
            string[] raw_payload_array;
            if (Regex.IsMatch(raw_input, payload_pattern_c))
            {
                //c语言格式的shellcode,转成 csharp 格式
                raw_input = raw_input.Replace("\"", "").Replace("\\", ",0").Replace(";", "").Replace("=", "{").Replace("{,", "{ ") + " }";
            }
            string raw_payload = Regex.Matches(raw_input, payload_pattern_csharp)[0].Value.Replace("{", "").Replace("}", "").Trim();
            raw_payload = raw_payload.TrimStart(',');
            raw_payload_array = raw_payload.Split(',');
            List<byte> byte_payload_list = new List<byte>();

            foreach (string i in raw_payload_array)
            {
                byte_payload_list.Add(string_to_int(i));
            }
            byte[] payload_result = byte_payload_list.ToArray();

            //加密payload并转换为字符串,准备写入文件
            byte[] encrypted_payload = Encrypter.Encrypt(KEY, payload_result);
            string string_encrypted_payload = string.Join(",", encrypted_payload);
            //MessageBox.Show(string_encrypted_payload);
            return string_encrypted_payload;
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static Dictionary<string, List<string>> ParseRuleFile(string ruleFilePath)
        {
            Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
            var contents = new StringReader(File.ReadAllText(ruleFilePath));
            string line = contents.ReadLine();
                while (line != null)
                {
                    try
                    {
                        //if the line contains a mitre_technique
                        if (line.Contains("mitre_technique_id "))
                        {
                            List<string> techniques = new List<string>();
                            //get all indexes from all technique ids and add them all to a list
                            IEnumerable<int> indexes = Regex.Matches(line, "mitre_technique_id ").Cast<Match>().Select(m => m.Index + "mitre_technique_id ".Length);
                            foreach (int index in indexes) 
                                techniques.Add(line.Substring(index, line.IndexOfAny(new [] { ',', ';' }, index) - index));
                            int head = line.IndexOf("msg:\"") + "msg:\"".Length;
                            int tail = line.IndexOf("\"", head);
                            string msg = line.Substring(head, tail - head);
                            head = line.IndexOf("sid:") + "sid:".Length;
                            tail = line.IndexOfAny(new char[] { ',', ';' }, head);
                            string sid = line.Substring(head, tail - head);
                            //for each found technique add the sid along with the message to the content
                            foreach( string technique in techniques)
                            {
                                if (res.ContainsKey(technique))
                                    res[technique].Add($"{sid} - {msg}");
                                else
                                    res.Add(technique, new List<string> { $"{sid} - {msg}" });
                            }
                        }
                        line = contents.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(line);
                        Console.WriteLine(e.Message);
                        line = contents.ReadLine();
                }
                }
                return res;
            }

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static MixedRealityToolkitModuleType GetModuleType(string filePath)
        {
            const string sentinelRegexPattern = @"^MRTK\.(?<module>[a-zA-Z]+)\.sentinel";
            string fileName = Path.GetFileName(filePath);
            var matches = Regex.Matches(fileName, sentinelRegexPattern);
            if (matches.Count == 1)
            {
                var moduleName = matches[0].Groups["module"].Value;
                MixedRealityToolkitModuleType moduleType;
                if (moduleNameMap.TryGetValue(moduleName, out moduleType))
                {
                    return moduleType;
                }
            }
            return MixedRealityToolkitModuleType.None;
        }

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

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

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

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

			var content = contentField.StringValue;

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

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

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

			var fragment = bestFragment.Trim();

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

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

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

public static string ValidateUnityTags(string text)
        {
            StringBuilder builder = new StringBuilder(text);

            Stack<Tag> tags = new Stack<Tag>();
            var matches = Regex.Matches(text, @"<(\/?)(\w+)(?:=.+?)?>");
            foreach (Match match in matches)
            {
                var tag = new Tag(
                    match.Groups[2].Value,
                    string.IsNullOrEmpty(match.Groups[1].Value));

                if (tag.IsOpeningTag)
                {
                    tags.Push(tag);
                }
                else
                {
                    if (tags.Count > 0 && tags.Peek().TagName == tag.TagName)
                    {
                        tags.Pop();
                    }
                    else
                    {
                        builder.Remove(match.Index, match.Length);
                    }
                }
            }
            while (tags.Count > 0)
            {
                builder.Append(tags.Pop().ClosingTag);
            }

            return builder.ToString();
        }

19 View Source File : MizMaker.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private bool AddLuaFileToEntries(Dictionary<string, byte[]> mizFileEntries, string mizEntryKey, string sourceFile, DCSMission mission = null)
        {
            if (string.IsNullOrEmpty(mizEntryKey) || mizFileEntries.ContainsKey(mizEntryKey) || string.IsNullOrEmpty(sourceFile)) return false;
            sourceFile = $"{BRPaths.INCLUDE_LUA}{sourceFile}";
            if (!File.Exists(sourceFile)) return false;

            string luaContent = File.ReadAllText(sourceFile);
            if (mission != null) // A mission was provided, do the required replacements in the file.
                luaContent = mission.ReplaceValues(luaContent);

            foreach (Match match in Regex.Matches(luaContent, "\\$.*?\\$"))
                BriefingRoom.PrintToLog($"Found a non-replacedigned value ({match.Value}) in Lua file \"{mizEntryKey}\".", LogMessageErrorLevel.Warning);
            luaContent = Regex.Replace(luaContent, "\\$.*?\\$", "0");

            mizFileEntries.Add(mizEntryKey, Encoding.UTF8.GetBytes(luaContent));
            return true;
        }

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

public static Pairs< string, object > Parse(string s)
    {
        var ret = new Pairs< string, object >();

		s = s.Trim();

		//check for enclosing brackets
		if (!Regex.Match(s, @"^{.*}$").Success)
			throw new InvalidOperationException("[Jsonizer] Bad json format while parsing '" + s + "'");
		
		//remove enclosing brackets
		s = s.Substring(1);
		s = s.Substring(0, s.Length - 1);

		//magic regex to parse exluding commas
		var datas = Regex.Matches(s, @"([\""].+?[\""]|\S+)\s*:\s*([\(].+?[\)]|[^,]+)")
            .Cast< Match >()
            .Select(m => m.Value);

		foreach (var data in datas)
			ret.Add(ParsePart(data.Trim()));

        return ret;
    }

19 View Source File : TemplateShaderData.cs
License : MIT License
Project Creator : alexismorin

public static TemplateShaderInfo CreateShaderData( string body )
		{
			int nameBegin = body.IndexOf( TemplatesManager.TemplateShaderNameBeginTag );
			if( nameBegin < 0 )
			{
				// Not a template
				return null;
			}

			TemplateShaderInfo shaderData = null;
			//SHADER
			MatchCollection shaderMatch = Regex.Matches( body, "\\bShader\\b" );
			if( shaderMatch.Count > 0 )
			{
				//SUBSHADER
				MatchCollection subShaderMatch = Regex.Matches( body, TemplatesManager.TemplateMPSubShaderTag );
				int subShaderAmount = subShaderMatch.Count;
				if( subShaderAmount > 0 )
				{
					shaderData = new TemplateShaderInfo();
					shaderData.Body = body;
					int length = subShaderMatch[ 0 ].Index - shaderMatch[ 0 ].Groups[ 0 ].Index;
					shaderData.Properties = body.Substring( shaderMatch[ 0 ].Index, length );
					shaderData.PropertyStartIdx = body.IndexOf( TemplatesManager.TemplatePropertyTag );

					for( int subShaderIdx = 0; subShaderIdx < subShaderAmount; subShaderIdx++ )
					{
						TemplateSubShaderInfo subShaderData = new TemplateSubShaderInfo();
						int subshaderBeginIndex = subShaderMatch[ subShaderIdx ].Index;
						int subShaderEndIndex = ( subShaderIdx == ( subShaderAmount - 1 ) ) ? body.Length - 1 : subShaderMatch[ subShaderIdx + 1 ].Index;
						subShaderData.Data = body.Substring( subshaderBeginIndex, subShaderEndIndex - subshaderBeginIndex );
						subShaderData.StartIdx = subshaderBeginIndex;

						//Preplaced
						MatchCollection preplacedMatch = Regex.Matches( subShaderData.Data, TemplatesManager.TemplatePreplacedTagPattern );
						if( preplacedMatch.Count == 0 )
						{
							preplacedMatch = Regex.Matches( subShaderData.Data, TemplatesManager.TemplateMPPreplacedTag );
						}

						int preplacedCount = preplacedMatch.Count;
						if( preplacedCount > 0 )
						{
							int lastPreplacedIndex = subShaderData.Data.LastIndexOf( TemplatesManager.TemplatePreplacedesEndTag );
							if( lastPreplacedIndex < 0 )
							{
								lastPreplacedIndex = subShaderData.Data.Length - 1;
							}

							subShaderData.Modules = subShaderData.Data.Substring( 0, preplacedMatch[ 0 ].Index );
							for( int preplacedIdx = 0; preplacedIdx < preplacedCount; preplacedIdx++ )
							{
								int preplacedBeginIndex = preplacedMatch[ preplacedIdx ].Index;
								int preplacedEndIdx = ( preplacedIdx == ( preplacedCount - 1 ) ) ? lastPreplacedIndex : preplacedMatch[ preplacedIdx + 1 ].Index;
								TemplatePreplacedInfo preplacedData = new TemplatePreplacedInfo();
								preplacedData.Data = subShaderData.Data.Substring( preplacedBeginIndex, preplacedEndIdx - preplacedBeginIndex );
								preplacedData.GlobalStartIdx = subshaderBeginIndex + preplacedBeginIndex;
								preplacedData.LocalStartIdx = preplacedBeginIndex;
								subShaderData.Preplacedes.Add( preplacedData );
							}
							shaderData.SubShaders.Add( subShaderData );
						}
					}
				}
			}
			return shaderData;
		}

19 View Source File : TemplateShaderData.cs
License : GNU General Public License v3.0
Project Creator : alexismorin

public static TemplateShaderInfo CreateShaderData( string body )
		{
			int nameBegin = body.IndexOf( TemplatesManager.TemplateShaderNameBeginTag );
			if( nameBegin < 0 )
			{
				// Not a template
				return null;
			}

			TemplateShaderInfo shaderData = null;
			//SHADER
			MatchCollection shaderMatch = Regex.Matches( body, "\\bShader\\b" );
			if( shaderMatch.Count > 0 )
			{
				//SUBSHADER
				MatchCollection subShaderMatch = Regex.Matches( body, TemplatesManager.TemplateMPSubShaderTag );
				int subShaderAmount = subShaderMatch.Count;
				if( subShaderAmount > 0 )
				{
					shaderData = new TemplateShaderInfo();
					shaderData.Body = body;
					int length = subShaderMatch[ 0 ].Index - shaderMatch[ 0 ].Groups[ 0 ].Index;
					shaderData.Properties = body.Substring( shaderMatch[ 0 ].Index, length );
					shaderData.PropertyStartIdx = body.IndexOf( TemplatesManager.TemplatePropertyTag );

					for( int subShaderIdx = 0; subShaderIdx < subShaderAmount; subShaderIdx++ )
					{
						TemplateSubShaderInfo subShaderData = new TemplateSubShaderInfo();
						int subshaderBeginIndex = subShaderMatch[ subShaderIdx ].Index;
						int subShaderEndIndex = ( subShaderIdx == ( subShaderAmount - 1 ) ) ? body.Length - 1 : subShaderMatch[ subShaderIdx + 1 ].Index;
						subShaderData.Data = body.Substring( subshaderBeginIndex, subShaderEndIndex - subshaderBeginIndex );
						subShaderData.StartIdx = subshaderBeginIndex;

						//Preplaced
						MatchCollection preplacedMatch = Regex.Matches( subShaderData.Data, TemplatesManager.TemplateMPPreplacedTag );
						int preplacedCount = preplacedMatch.Count;
						if( preplacedCount > 0 )
						{
							subShaderData.Modules = subShaderData.Data.Substring( 0, preplacedMatch[ 0 ].Index );
							for( int preplacedIdx = 0; preplacedIdx < preplacedCount; preplacedIdx++ )
							{
								int preplacedBeginIndex = preplacedMatch[ preplacedIdx ].Index;
								int preplacedEndIdx = ( preplacedIdx == ( preplacedCount - 1 ) ) ? subShaderData.Data.Length - 1 : preplacedMatch[ preplacedIdx + 1 ].Index;
								TemplatePreplacedInfo preplacedData = new TemplatePreplacedInfo();
								preplacedData.Data = subShaderData.Data.Substring( preplacedBeginIndex, preplacedEndIdx - preplacedBeginIndex );
								preplacedData.GlobalStartIdx = subshaderBeginIndex + preplacedBeginIndex;
								preplacedData.LocalStartIdx = preplacedBeginIndex;
								subShaderData.Preplacedes.Add( preplacedData );
							}
							shaderData.SubShaders.Add( subShaderData );
						}
					}
				}
			}
			return shaderData;
		}

19 View Source File : TestRS232OnlyTwoWayComPort.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void GetPresetStatus(string param)
        {
            string MessageHelp = "TGetPresetStatus" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                var status = _ComPort.GetPresetStringStatus(Message);
                CrestronConsole.ConsoleCommandResponse("CMD:Preset String {0} Status is {1}", Message, status);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestRS232OnlyTwoWayComPort.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void ChangeDelimiter(string param)
        {
            string MessageHelp = "TTransmitData" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Changing Delimiter to: {0}", Message);
                _ComPort.delimiter = Message;
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestTwoWayComPort.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitPreset(string param)
        {
            string MessageHelp = "TTransmitMessage" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Message: {0} through Com Port", Message);
                _ComPort.SendPresetString(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDeviceControl.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

static void ChangeInputName(string Options)
        {
            string MessageHelp = "TInputName InputNo(1-10) Name";
            var commands = Regex.Matches(Options, "[\\w]+|\\\"[^\\\"]*\\\"");
            int InputNumber;
            string Name;
            try
            {
                Name = commands[1].Value;
                InputNumber = int.Parse(commands[0].Value);
            }
            catch(Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return;
            }
            if (InputNumber > 0 && InputNumber <= 10)
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Changing input {0} name to : {1}", InputNumber, Name);
                switch (InputNumber)
                {
                    case 1:
                        _DeviceControl.Input_1_Name(Name);
                        break;
                    case 2:
                        _DeviceControl.Input_2_Name(Name);
                        break;
                    case 3:
                        _DeviceControl.Input_3_Name(Name);
                        break;
                    case 4:
                        _DeviceControl.Input_4_Name(Name);
                        break;
                    case 5:
                        _DeviceControl.Input_5_Name(Name);
                        break;
                    case 6:
                        _DeviceControl.Input_6_Name(Name);
                        break;
                    case 7:
                        _DeviceControl.Input_7_Name(Name);
                        break;
                    case 8:
                        _DeviceControl.Input_8_Name(Name);
                        break;
                    case 9:
                        _DeviceControl.Input_9_Name(Name);
                        break;
                    case 10:
                        _DeviceControl.Input_10_Name(Name);
                        break;

                    default:
                        break;
                }
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDeviceControl.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

static void ChangeOutputName(string Options)
        {
            string MessageHelp = "TOutputName InputNo(1-1) Name";
            var commands = Regex.Matches(Options, "[\\w]+|\\\"[^\\\"]*\\\"");
            int OutputNumber;
            string Name;
            try
            {
                Name = commands[1].Value;
                OutputNumber = int.Parse(commands[0].Value);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return;
            }
            if (OutputNumber > 0 && OutputNumber <= 1)
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Changing output {0} name to : {1}", OutputNumber, Name);
                switch (OutputNumber)
                {
                    case 1:
                        _DeviceControl.Output_Name(Name);
                        break;
                    default:
                        break;
                }
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMPS3TwoWaySerialDriver.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitData(string param)
        {
            string MessageHelp = "TTransmitData" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Data: {0} through Com Port", Message);
                _ComPort.tx(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMRmc4KZ100C.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void GetPresetStatus(string param)
        {
            string MessageHelp = "TGetPresetStatusDMRX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                var status = _ComPort.GetPresetStringStatus(Message);
                CrestronConsole.ConsoleCommandResponse("CMD:Preset String {0} Status is {1}", Message, status);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMRmc4KZ100C.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void SendCECDMMessage(string message)
        {
            string MessageHelp = "TCECDMMessageRxDMRX" + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _CECDMDevice.Transmit_CEC_Message(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMRmc4KZ100C.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void SendCECHDMIMessage(string message)
        {
            string MessageHelp = "TCECHDMIMessageRxDMRX" + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _CECHDCPDevice.Transmit_CEC_Message(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMTx4K100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitData(string param)
        {
            string MessageHelp = "TTransmitDataDMTX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Data: {0} through Com Port", Message);
                _ComPort.tx(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestUSBPort.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void OutputReport(string message)
        {
            string MessageHelp = "TOutputReport" + _UsbHid.Name + " message";
            var commands = Regex.Matches(message, "[0-9A-F\\:]+");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Output Report Data: {0} through USB", Message);
                _UsbHid.Output_Report(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestUSBPort.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void FeatureReport(string message)
        {
            string MessageHelp = "TFeatureReport" + _UsbHid.Name + " message";
            var commands = Regex.Matches(message, "[0-9A-F\\:]+");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Feature Report Data: {0} through USB", Message);
                _UsbHid.Feature_Report(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMOutput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void HDMICECTx(string message)
        {
            string MessageHelp = "THDMICECTx" + _DMOutput.DMOutputPort + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _DMOutput.HDMI_CEC_Transmit(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMRmc4KZ100C.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitData(string param)
        {
            string MessageHelp = "TTransmitDataDMRX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Data: {0} through Com Port", Message);
                _ComPort.tx(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMRmc4KZ100C.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitPreset(string param)
        {
            string MessageHelp = "TTransmitMessageDMRX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Message: {0} through Com Port", Message);
                _ComPort.SendPresetString(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMRmc4KZ100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void SendCECMessage(string message)
        {
            string MessageHelp = "TCECHDMIMessageRxDMRX" + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _CECDevice.Transmit_CEC_Message(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMTx4K100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void TransmitPreset(string param)
        {
            string MessageHelp = "TTransmitMessageDMTX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Transmitting Message: {0} through Com Port", Message);
                _ComPort.SendPresetString(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMTx4K100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void GetPresetStatus(string param)
        {
            string MessageHelp = "TGetPresetStatusDMTX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                var status = _ComPort.GetPresetStringStatus(Message);
                CrestronConsole.ConsoleCommandResponse("CMD:Preset String {0} Status is {1}", Message, status);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMTx4K100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void ChangeDelimiter(string param)
        {
            string MessageHelp = "TTransmitDataDMTX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Changing Delimiter to: {0}", Message);
                _ComPort.delimiter = Message;
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestHDMIInput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void SendCECMessage(string message)
        {
            string MessageHelp = "TCECMessage" + _HDMIInput.HDMIInputPort + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _HDMIInput.Transmit_CEC_Message(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMRmc4KZ100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

private void ChangeDelimiter(string param)
        {
            string MessageHelp = "TTransmitDataDMRX" + _ComPort.Name + " message";
            var commands = Regex.Matches(param, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Changing Delimiter to: {0}", Message);
                _ComPort.delimiter = Message;
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);

        }

19 View Source File : TestDMOutput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void DMCECTx(string message)
        {
            string MessageHelp = "TDMCECTx" + _DMOutput.DMOutputPort + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _DMOutput.DM_CEC_Transmit(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : TestDMTx4K100C1G.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

void SendCECMessage(string message)
        {
            string MessageHelp = "TCECMessagHDMITxDMTX" + " message";
            var commands = Regex.Matches(message, "\\\".*?\\\"|\\S*");
            string Message = "";
            try
            {
                Message = commands[0].Value.Replace("\"", string.Empty);
                Message = Regex.Unescape(Message);
            }
            catch
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
            }
            if (Message != "")
            {
                CrestronConsole.ConsoleCommandResponse("CMD:Sending Message {0} through CEC", Message);
                _CECDevice.Transmit_CEC_Message(Message);
            }
            else CrestronConsole.ConsoleCommandResponse(MessageHelp);
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

private string FindMatch(string text, string pattern)
        {
            string result = null;
            if (!String.IsNullOrWhiteSpace(text))
            {
                MatchCollection matches = Regex.Matches(text, pattern);
                // Force the regular expression engine to find all matches at once (otherwise it enumerates match-by-match lazily).
                var count = matches.Count;
                if (count > 0)
                {
                    var match = matches[count - 1]; // Last match
                    result = match.Groups[1].Value; // Groups[0] is the match itself.
                }
            }
            return result;
        }

19 View Source File : Clue.cs
License : MIT License
Project Creator : anthonychu

public int CalculateQuality()
        {
            var score = 0; // the higher the better

            var nonLettersCount = Regex.Matches(Answer, "[^a-zA-Z ]").Count;
            score -= nonLettersCount;

            var isAllDigits = Regex.IsMatch(Answer, @"^\d+$");
            if (isAllDigits)
            {
                score -= 10;
            }

            if (string.IsNullOrWhiteSpace(Question) || string.IsNullOrWhiteSpace(Answer))
            {
                score -= 100;
            }
            else if (Regex.IsMatch(Question, @"\bseen here\b", RegexOptions.IgnoreCase))
            {
                // "seen here" usually indicates a visual clue
                score -= 50;
            }

            if (Answer.Length > 16)
            {
                score -= 10; // deduct points if too long
            }

            if (this.Value > 300)
            {
                score -= 5;
            }

            if (this.Value > 500)
            {
                score -= 5;
            }

            if (this.Value >= 800)
            {
                score -= 5;
            }

            return score;
        }

19 View Source File : SoqlApi.cs
License : MIT License
Project Creator : apexsharp

public static string ConvertSoql(string soql, params object[] param)
        {
            var matches = Regex.Matches(soql, "(\\:\\S+)");
            if (matches.Count == param.Length)
            {
                for (int i = 0; i < param.Length; i++)
                {
                    if (param[i].GetType().Name == "Int32")
                    {
                        soql = soql.Replace(matches[i].Value, " " + param[i] + " ");
                    }
                    else
                    {
                        soql = soql.Replace(matches[i].Value, "'" + param[i] + "'");
                    }
                }
            }
            else
            {
                Log.Logger.Error("Fail in ConvertSoql");
            }
            return soql;
        }

19 View Source File : AddressUtility.cs
License : Apache License 2.0
Project Creator : Appdynamics

public static string ParseEntireColumnSelections(string address)
        {
            string parsedAddress = address;
            var matches = Regex.Matches(address, "[A-Z]+:[A-Z]+");
            foreach (Match match in matches)
            {
                AddRowNumbersToEntireColumnRange(ref parsedAddress, match.Value);
            }
            return parsedAddress;
        }

19 View Source File : DBCFile.cs
License : MIT License
Project Creator : Aptiv-WLL

private void Parse(string s)
        {
            NS_Lib = new Dictionary<string, int>();
            BS_Lib = new Dictionary<string, int>();
            MsgSendTypes = new Dictionary<int, string>();
            ecus = new Dictionary<string, DBCECU>();
            messages = new Dictionary<string, DBCMessage>();
            attributes = new Dictionary<string, Dictionary<string, List<string>>>();
            signalGroups = new Dictionary<string, List<IDBCSignal>>();

            #region --- Strings for matches ---
            string NS = @"NS_[\t ]*:[\r\t ]*\n(\t[\w]+[\r\t ]*\n)*";
            string BU = @"BU_\s *:(\s +.*)*";
            string BOline = @"BO_\s+\d+\s+\w+:\s*\d+\s+\w+";
            string SGline = @"SG_\s+\w+\s*\w*\s*:\s*\d+\|\[email protected][01][+-]\s+\([\d.-]*,[\d.-]*\)\s+\[.*\|.*\]\s+"".*""(\s+\w+,*\s*)+";
            string BO = BOline + @"\s+(" + SGline + @")*";
            string CM = @"CM_\s+\w+\s+\w+(\s+\w+)*\s+""([^""]*)*""";
            string BA_DEF = @"BA_DEF_\s+.*;";
            string BA_DEF_DEF = @"BA_DEF_DEF_\s+.*;";
            string BA = @"BA_\s+.*;";
            string VAL = @"VAL_\s+.*;";
            //string SIG_GROUP = @"";
            #endregion

            // init some values
            string[] tmp = new string[0];
            int i = -1, DataLength = 0;
            string ECU_Name = "", Msg_Name = "", Snl_name = "", MsgIDHex = "";
            string AttributeName = "", AttributeValue = "";
            try
            {
                #region --- New Symbols ---
                foreach (Match m in Regex.Matches(s, NS))
                {
                    // Remove NS_ and split by whitespace
                    string[] keys = m.Value.Split('\n');

                    // Add to NS lib if not already there
                    for (int ki = 1; ki < keys.Length; ki++)
                        if (!NS_Lib.ContainsKey(keys[ki]) && !string.IsNullOrEmpty(keys[ki]))
                            NS_Lib.Add(keys[ki], NS_Lib.Count);
                }
                #endregion

                #region --- ECUs ---
                foreach (Match m in Regex.Matches(s, BU))
                {
                    // Remove BU_ and split by whitespace
                    tmp = Regex.Split(m.Value.Replace("BU_", ""), @"\s+");

                    // Add to ECU libs
                    foreach (string str in tmp)
                        if (!ecus.ContainsKey(str))
                        {
                            //ECU_Lib.Add(str, ECU_Lib.Count);
                            ecus.Add(str, new DBCECU(tmp[i]));
                        }
                }
                #endregion

                #region --- Messages & Signals ---
                foreach (Match m in Regex.Matches(s, BO))
                {
                    // Deal with Message line: BO_ Tag | Message ID | Message Name | Message Length (bytes) | ECU
                    string messageLine = Regex.Match(m.Value, BOline).Value;

                    //split by whitespace
                    tmp = Regex.Split(messageLine.Replace(":", ""), @"\s+");

                    // Message Attributes
                    ECU_Name = tmp[4];
                    Msg_Name = tmp[2];
                    int midLen = tmp[1].Length > 4 ? 4 : 2;
                    MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                    DataLength = Convert.ToInt32(tmp[3]);


                    //If ECU doesn't exist, create it
                    if (!ecus.ContainsKey(ECU_Name))
                        ecus.Add(ECU_Name, new DBCECU(ECU_Name));

                    // Add a new message
                    var newMessage = new DBCMessage(midLen + DataLength, ecus[ECU_Name], MsgIDHex, Msg_Name);
                    messages.Add(MsgIDHex, newMessage);
                    
                    // Add message to Messages dictionary in current ECU
                    if(!ecus[ECU_Name].Messages.ContainsKey(MsgIDHex)) {
                        ecus[ECU_Name].Messages[MsgIDHex] = (IDBCMessage)newMessage; 
                    }
                    
                    // Deal with signal line:
                    // SG_ Tag | Signal ID | Optional Multiplexer | Start Bit + Length (bits) + Byte Direction | (Factor, Offset) | Physical Range [min,max] | Physical Units | Response ECU
                    foreach (Match sig in Regex.Matches(m.Value, SGline))
                    {
                        int multiplexer = 0; // 1 if there is a multiplexer, 0 if not
                        if (Regex.IsMatch(sig.Value, @"\w+\s+\w+\s+\w+\s*:"))
                            multiplexer = 1;

                        tmp = Regex.Split(Regex.Replace(sig.Value, @"[\(\)\[\]\|""@,:]", " "), @"\s+");

                        Snl_name = tmp[1];

                        // Signal Attributes
                        int startBit = Convert.ToInt32(tmp[2 + multiplexer]);
                        int length = Convert.ToInt32(tmp[3 + multiplexer]);
                        IntDescriptor descriptor = (tmp[4 + multiplexer][1] == '+') ? IntDescriptor.Unsigned : IntDescriptor.Signed;
                        ByteOrder byteOrder;
                        if (tmp[4 + multiplexer][0] == '1')
                            byteOrder = ByteOrder.Intel;
                        else byteOrder = ByteOrder.Motorola;
                        double factor = Convert.ToDouble(tmp[5 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double offset = Convert.ToDouble(tmp[6 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double physMin = Convert.ToDouble(tmp[7 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double physMax = Convert.ToDouble(tmp[8 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        string physUnits = tmp[9 + multiplexer];

                        //If physMin and physMax are both 0, then physMax is as high as the largest bitvalue
                        physMax = (physMin == 0 && physMax == 0) ? (1 << length) : physMax;

                        // These values should be 0 and (2 << length - 1)
                        ulong normMin = (ulong)((physMin - offset) / factor);
                        ulong normMax = (ulong)((physMax - offset) / factor);
                        double res = (physMax - physMin) / (normMax - normMin);
                        if (double.IsInfinity(res) || double.IsNaN(res))
                            res = 1;

                        // Responce ECUs
                        for (i = 10 + multiplexer; i < tmp.Length; i++)
                        {
                            if (!ecus.ContainsKey(tmp[i]))
                                ecus.Add(tmp[i], new DBCECU(tmp[i]));
                            if (!ecus[tmp[i]].RxMessages.ContainsKey(MsgIDHex))
                                ecus[tmp[i]].RxMessages.Add(MsgIDHex, messages[MsgIDHex]);
                        }

                        int old = startBit;

                        // TODO: verify this is needed.
                        // account for motorola being inverse
                        if (byteOrder == ByteOrder.Motorola)
                        {
                            int newStartBit = startBit;
                            for (i = 1; i < length; i++)
                            {
                                if (newStartBit % 8 == 0)
                                    newStartBit += 15;
                                else
                                    newStartBit -= 1;
                            }
                            startBit = newStartBit;
                        }

                        // Add a new signal
                        messages[MsgIDHex].Signals.Add(Snl_name, new DBCSignal(ecus[ECU_Name],
                            messages[MsgIDHex], (uint)startBit, Snl_name, (uint)length, 0, 0,
                            physMax, physMin, normMax, normMin, res, physUnits, descriptor,
                            byteOrder, offset, sig.Value));
                    }
                }




                #endregion

                #region --- Functionality Description (comments) ---
                foreach (Match m in Regex.Matches(s, CM))
                {
                    /*  Note:
                     *  Only existing signals can have comments parsed for them,
                     *  there is no way to generate a new signal or message from
                     *  a comment statement. */

                    if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        tmp = Regex.Split(m.Value, @"\s+");
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[2]).ToString("X3");
                        if (messages.ContainsKey(MsgIDHex))
                        {
                            Snl_name = tmp[3];
                            if (messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                            {
                                string function = "";
                                for (i = 4; i < tmp.Length; i++)
                                    function += (tmp[i] + " ").Replace("\"", "");
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).Function = function;
                            }
                        }
                    }
                }
                #endregion

                #region --- Base Attribute Definitions ---
                foreach (Match m in Regex.Matches(s, BA_DEF))
                {
                    string attributeName;
                    string attributeType;
                    string tag = "Definition";
                    List<string> attributeSettings = new List<string>();
                    tmp = Regex.Split(m.Value, @"\s+");

                    if (Regex.IsMatch(m.Value, @"BU_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));
                    }
                    else if (Regex.IsMatch(m.Value, @"BO_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));

                        // OG code... fix in future
                        switch (attributeName)
                        {
                            case "GenMsgSendType":  //Message send type(cyclic, spontaneous, etc..)
                                string[] values = tmp[tmp.Length - 1].Split(',');
                                for (int k = 0; k < values.Length; k++)
                                {
                                    //k is Enum int value, values[k] is string it represents
                                    MsgSendTypes.Add(k, values[k].Replace("\"", "").Replace(";", ""));
                                }
                                break;
                            case "GenMsgCycleTime":
                                break;
                            case "GenMsgStartDelayTime":
                                break;
                            case "GenMsgDelayTime":
                                break;
                            default:
                                break;
                        }
                    }
                    else if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));
                    }
                    else
                    {
                        // extract info
                        attributeName = tmp[1].Replace("\"", "");
                        attributeType = tmp[2];
                        for (int j = 3; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));

                        // add to dict
                        if (attributes.ContainsKey(attributeName))
                        {
                            if (attributes[attributeName].ContainsKey(tag))
                                attributes[attributeName][tag].Concat(attributeSettings);
                            else
                                attributes[attributeName].Add(tag, attributeSettings);
                        }
                        else
                        {
                            attributes.Add(attributeName, new Dictionary<string, List<string>>());
                            attributes[attributeName].Add(tag, attributeSettings);
                        }
                    }

                }
                #endregion

                #region --- Base Attribute Definitions Defaults ---
                foreach (Match m in Regex.Matches(s, BA_DEF_DEF))
                {
                    string tag = "Default";
                    tmp = Regex.Split(Regex.Replace(m.Value, @"[;""]", ""), @"\s+");
                    if (tmp.Length < 3)
                        continue;
                    string attr = tmp[1];
                    string val = tmp[2];

                    if (attributes.ContainsKey(attr))
                    {
                        if (attributes[attr].ContainsKey(tag))
                            attributes[attr][tag].Add(val);
                        else
                            attributes[attr].Add(tag, new List<string>() { val });
                    }
                    else
                        attributes.Add(attr, new Dictionary<string, List<string>>() { { tag, new List<string>() { val } } });
                }
                #endregion

                #region --- Base Attributes ---
                foreach (Match m in Regex.Matches(s, BA))
                {
                    string tag = "Setting";
                    string attributeName;
                    string attributeValue;
                    List<string> attributeSettings = new List<string>();

                    //modified regex check to ignore spaces inside of quotes
                    tmp = Regex.Split(m.Value, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

                    if (Regex.IsMatch(tmp[2], @"BO_"))
                    {
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[3]).ToString("X3");

                        //Handle attributes if MsgID exists
                        if (messages.ContainsKey(MsgIDHex))
                        {
                            attributeName = tmp[1].Replace("\"", "");
                            attributeValue = tmp[4].Replace(";", "");
                            switch (attributeName)
                            {
                                case "GenMsgCycleTime": //Cycle time
                                    messages[MsgIDHex].CycleTime = uint.Parse(attributeValue);
                                    break;
                                case "GenMsgSendType": //Launch type(cyclic, spontaneous, etc.)
                                    messages[MsgIDHex].LaunchType = MsgSendTypes[int.Parse(attributeValue)];
                                    break;
                                case "GenMsgDelayTime":
                                    messages[MsgIDHex].DelayTime = int.Parse(attributeValue);
                                    break;
                            }
                        }
                    }
                    else if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[3]).ToString("X3");
                        Snl_name = tmp[4];

                        AttributeName = tmp[1].Replace("\"", "");
                        AttributeValue = "";
                        for (i = 5; i < tmp.Length; i++)
                            AttributeValue += (tmp[i] + " ").Replace("\"", "").Replace(";", "");

                        // Check and add
                        if (messages.ContainsKey(MsgIDHex) &&
                            messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                            ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).Attributes.Add(AttributeName, AttributeValue);
                    }
                    else
                    {
                        if (attributes.ContainsKey(tmp[1]))
                        {
                            if (attributes[tmp[1]].ContainsKey(tag))
                                attributes[tmp[1]][tag].Add(tmp[2]);
                            else
                                attributes[tmp[1]].Add(tag, new List<string>() { tmp[2] });
                        }
                        else
                            attributes.Add(tmp[1], new Dictionary<string, List<string>>() { { tag, new List<string>() { tmp[2] } } });
                        //break;
                    }
                }
                #endregion

                #region --- Specified Signal Values ---

                foreach (Match m in Regex.Matches(s, VAL))
                {
                    tmp = Regex.Split(m.Value, @"\s+");
                    MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                    Snl_name = tmp[2];

                    foreach (Match val in Regex.Matches(m.Value, "\\d+\\s+\".*?\""))
                    {
                        tmp = Regex.Split(val.Value.Replace("\"", " "), @"\s+");

                        long key = long.Parse(tmp[0]);
                        tmp[0] = "";
                        string specifiedValue = string.Join<string>(" ", tmp).Trim();

                        // Check and add
                        if (messages.ContainsKey(MsgIDHex) &&
                            messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                        {
                            if (messages[MsgIDHex].Signals[Snl_name].SpecifiedValues.ContainsKey(key))
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).SpecifiedValues[key] = specifiedValue;
                            else
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).SpecifiedValues.Add(key, specifiedValue);
                        }
                    }
                }

                #endregion
            }
            catch (DatabaseLoadingException)
            {
                throw;
            }
            /*catch (Exception e)
            {
                throw new DatabaseLoadingException("Parsing of the given DBC file failed.", e, this, "");
            }*/

            #region old code section for Signal Groups
            /* 
                OG SIG_GROUP_ parsing below

                        #region SIG_GROUP_ (Signal Groupings)
                        case "SIG_GROUP_":

                            // Remove the tag and use space as a delimiter
                            tmp = AcquireValues(str);

                            MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                            ECU_name = MsgID_to_ECUname[MsgIDHex];
                            string Group_name = tmp[2];

                            for (int itm = 5; itm < tmp.Length; itm++)
                            {
                                Snl_name = tmp[itm];
                                if (SignalGroups.ContainsKey(Group_name))
                                    SignalGroups[Group_name].Add(Messages[MsgIDHex].Signals[Snl_name]);
                                else
                                    SignalGroups.Add(Group_name, new List<IDBCSignal>() { Messages[MsgIDHex].Signals[Snl_name] });
                            }

                            break;
                        #endregion
            } 
            */
            #endregion
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : arcusmaximus

private static void replacedignOpcodeHandlerNames(string filePath)
        {
            string content = File.ReadAllText(filePath);
            foreach (Match match in Regex.Matches(content, @"\w{8}    push 14FE0\r\n\w{8}    push (\w+)\r\n\w{8}    push 2\r\n\w{8}    shl\r\n\w{8}    add\r\n\w{8}    push (sub_\w{8})"))
            {
                string opcode = match.Groups[1].Value;
                string funcName = match.Groups[2].Value;
                content = content.Replace(funcName, $"Opcode{opcode}");
            }
            File.WriteAllText(filePath, content);
        }

19 View Source File : AssTransformTagHandler.cs
License : MIT License
Project Creator : arcusmaximus

public override void Handle(replacedTagContext context, string arg)
        {
            if (!TryParseArgs(context, arg, out DateTime startTime, out DateTime endTime, out float accel, out string modifiers))
                return;

            context.Line.AndroidDarkTextHackAllowed = false;

            foreach (Match match in Regex.Matches(modifiers, @"\\(?<tag>\d?[a-z]+)(?<arg>[^\\]*)"))
            {
                if (TransformTagHandlers.TryGetValue(match.Groups["tag"].Value, out TransformTagHandler handler))
                    handler(context, startTime, endTime, accel, match.Groups["arg"].Value.Trim());
            }
        }

19 View Source File : StringUtil.cs
License : MIT License
Project Creator : arcusmaximus

public static string FancifyQuotes(string str, string tagRegex = null)
        {
            MatchCollection tagMatches = tagRegex != null ? Regex.Matches(str, tagRegex) : null;
            str = Regex.Replace(
                str,
                @"(?<=^|[ ""])'",
                m => IsInTag(m.Index) ? m.Value : "‘"
            );
            str = Regex.Replace(
                str,
                @"'",
                m => IsInTag(m.Index) ? m.Value : "’"
            );
            str = Regex.Replace(
                str,
                @"(?<=^| )""",
                m => IsInTag(m.Index) ? m.Value : "“"
            );
            str = Regex.Replace(
                str,
                @"""",
                m => IsInTag(m.Index) ? m.Value : "”"
            );
            return str;

            bool IsInTag(int index)
            {
                if (tagMatches == null)
                    return false;

                return tagMatches.Cast<Match>().Any(m => index >= m.Index && index < m.Index + m.Length);
            }
        }

19 View Source File : AssDocument.cs
License : MIT License
Project Creator : arcusmaximus

internal void CreateTagSections(replacedLine line, string text, replacedTagContext context)
        {
            text = Regex.Replace(text, @"(?:\\N)+$", "");
            HashSet<string> handledWholeLineTags = new HashSet<string>();

            int start = 0;
            foreach (Match tagGroupMatch in Regex.Matches(text, @"\{(.*?)\}"))
            {
                int end = tagGroupMatch.Index;

                if (end > start || (context.Section.Duration > TimeSpan.Zero && Regex.IsMatch(tagGroupMatch.Groups[1].Value, @"\\k\s*\d+")))
                {
                    if (end == start)
                        context.Section.Text = "\x200B";
                    else
                        context.Section.Text = ResolveEscapeSequences(text.Substring(start, end - start));

                    line.Sections.Add(context.Section);

                    context.Section = (replacedSection)context.Section.Clone();
                    context.Section.Text = null;
                    context.Section.Duration = TimeSpan.Zero;
                }

                foreach (Match tagMatch in Regex.Matches(tagGroupMatch.Groups[1].Value, @"\\(?<tag>fn|r|\d?[a-z]+)\s*(?<arg>\([^\(\)]*(?:\)|$)|[^\\\(\)]*)"))
                {
                    if (!_tagHandlers.TryGetValue(tagMatch.Groups["tag"].Value, out replacedTagHandlerBase handler))
                        continue;

                    if (handler.AffectsWholeLine && !handledWholeLineTags.Add(tagMatch.Groups["tag"].Value))
                        continue;

                    handler.Handle(context, tagMatch.Groups["arg"].Value.Trim());
                }

                start = tagGroupMatch.Index + tagGroupMatch.Length;
            }

            if (start < text.Length)
            {
                context.Section.Text = ResolveEscapeSequences(text.Substring(start, text.Length - start));
                line.Sections.Add(context.Section);
            }
        }

19 View Source File : MultiStyleLabel.cs
License : MIT License
Project Creator : arcusmaximus

private static Dictionary<string, string> ParseCssProperties(string properties)
        {
            return Regex.Matches(properties, @"([-\w]+)\s*:\s*([^;]+)\s*;")
                        .Cast<Match>()
                        .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
        }

19 View Source File : C3AddonImporter.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public async Task<C3Addon> Import(string path)
        {
            WindowManager.ShowLoadingOverlay(true);
            try
            {
                return await Task.Run(() =>
                {
                    var fi = new FileInfo(path);
                    var tmpPath = OptionsManager.CurrentOptions.DataPath + "\\tmp_c3";
                    if (Directory.Exists(tmpPath)) Directory.Delete(tmpPath, true);

                    //unzip c3addon to temp location
                    ZipFile.ExtractToDirectory(path, tmpPath);

                    var addon = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "addon.json")));
                    string type = addon["type"].ToString();
                    string id = addon["id"].ToString();

                    //todo: handle mixed c3addon with only c2runtime
                    bool c2Only = !File.Exists(Path.Combine(tmpPath, "c3runtime", $"{type}.js"));


                    if (type != "effect" && !c2Only)
                    {
                        string pluginEdit, pluginRun;

                        pluginEdit = File.ReadAllText(Path.Combine(tmpPath, $"{type}.js"));
                        pluginRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"{type}.js"));
                        string typeEdit = File.ReadAllText(Path.Combine(tmpPath, $"type.js"));
                        string typeRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"type.js"));
                        string instanceEdit = File.ReadAllText(Path.Combine(tmpPath, $"instance.js"));
                        string instanceRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"instance.js"));
                        string c2runtime = null;

                        if (Directory.Exists(Path.Combine(tmpPath, "c2runtime")))
                        {
                            c2runtime = File.ReadAllText(Path.Combine(tmpPath, "c2runtime", "runtime.js"));
                        }

                        PluginType pluginType = PluginType.SingleGlobalPlugin;
                        string pluginCat = "other";
                        switch (type)
                        {
                            case "plugin":
                                pluginType = pluginEdit.Contains("SetPluginType(\"world\")")
                                    ? PluginType.DrawingPlugin
                                    : PluginType.SingleGlobalPlugin;
                                pluginCat = Regex.Match(pluginEdit, @"PLUGIN_CATEGORY = ""(?<cat>).*""").Groups["cat"]
                                    .Value;
                                break;
                            case "behavior":
                                pluginType = PluginType.Behavior;
                                pluginCat = Regex.Match(pluginEdit, @"BEHAVIOR_CATEGORY = ""(?<cat>.*)""").Groups["cat"]
                                    .Value;
                                break;
                        }

                        if (string.IsNullOrWhiteSpace(pluginCat)) pluginCat = "other";

                        var ace = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "aces.json")));
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var prop = "\"properties\": " + (string.IsNullOrWhiteSpace(lang["properties"]?.ToString()) ? "{ }" : lang["properties"]);
                        var cats = "\"aceCategories\": " + (string.IsNullOrWhiteSpace(lang["aceCategories"]?.ToString()) ? "{ }" : lang["aceCategories"]);

                        //pasre ace implementations
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / ACTIONS");
                        var actFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "actions.js")));
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / CONDITION");
                        var cndFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "conditions.js")));
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / EXPRESSIONS");
                        var expFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "expressions.js")));

                        var actionList = new List<Models.Action>();
                        var conditionList = new List<Models.Condition>();
                        var expressionList = new List<Models.Expression>();

                        foreach (JProperty category in ace.Properties())
                        {
                            //parse actions
                            var ationJson = ace[category.Name]["actions"]?.ToString();
                            var actions = ationJson != null ? JArray.Parse(ationJson) : null;
                            if (actions != null)
                            {
                                foreach (var action in actions.Children<JObject>())
                                {
                                    var actionId = action["id"].ToString();
                                    var actionAce = action.ToString();
                                    var actionLang = $"\"{actionId}\":" + lang["actions"][actionId];
                                    var actionScript = action["scriptName"].ToString();
                                    var actionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (action["params"] != null && action["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = action["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    actionParams = string.Join(",", ep);
                                    //}

                                    actFuncs.TryGetValue(actionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"ACTION FUNCTION DEFINITION DOES NOT EXISTS => {actionScript.Trim()}");
                                        continue;
                                    }

                                    var act = new Models.Action
                                    {
                                        Id = actionId,
                                        Category = category.Name,
                                        Ace = actionAce,
                                        Language = actionLang,
                                        //Code = $"{actionScript}({string.Join(",", actionParams)}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(code) ?? string.Empty
                                    };

                                    actionList.Add(act);
                                }
                            }

                            //parse conditions
                            var conditionJson = ace[category.Name]["conditions"]?.ToString();
                            var conditions = conditionJson != null ? JArray.Parse(conditionJson) : null;
                            if (conditions != null)
                            {
                                foreach (var condition in conditions.Children<JObject>())
                                {
                                    var conditionId = condition["id"].ToString();
                                    var conditionAce = condition.ToString();
                                    var conditionLang = $"\"{conditionId}\":" + lang["conditions"][conditionId];
                                    var conditionScript = condition["scriptName"].ToString();
                                    var conditionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (condition["params"] != null && condition["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = condition["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    conditionParams = string.Join(",", ep);
                                    //}

                                    cndFuncs.TryGetValue(conditionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"CONDITION FUNCTION DEFINITION DOES NOT EXISTS => {conditionScript.Trim()}");
                                        continue;
                                    }
                                    var cnd = new Models.Condition()
                                    {
                                        Id = conditionId,
                                        Category = category.Name,
                                        Ace = conditionAce,
                                        Language = conditionLang,
                                        //Code = $"{conditionScript}({string.Join(",", conditionParams)}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(code) ?? string.Empty
                                    };

                                    conditionList.Add(cnd);
                                }
                            }

                            //parse expression
                            var expressionJson = ace[category.Name]["expressions"]?.ToString();
                            var expressions = expressionJson != null ? JArray.Parse(expressionJson) : null;
                            if (expressions != null)
                            {
                                foreach (var expression in expressions.Children<JObject>())
                                {
                                    var expressionId = expression["id"].ToString();
                                    var expressionAce = expression.ToString();
                                    var expressionLang = $"\"{expressionId}\":" + lang["expressions"][expressionId];
                                    var expressionScript = expression["expressionName"].ToString();
                                    var expressionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (expression["params"] != null && expression["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = expression["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    expressionParams = string.Join(",", ep);
                                    //}

                                    expFuncs.TryGetValue(expressionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"EXPRESSION FUNCTION DEFINITION DOES NOT EXISTS => {expressionScript.Trim()}");
                                        continue;
                                    }
                                    var exp = new Models.Expression()
                                    {
                                        Id = expressionId,
                                        Category = category.Name,
                                        Ace = expressionAce,
                                        Language = expressionLang,
                                        //Code = $"{expressionScript}({expressionParams}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(expFuncs[expressionScript.Trim()]) ??
                                               string.Empty
                                    };

                                    expressionList.Add(exp);
                                }
                            }
                        }

                        var thirdPartyFiles = new List<ThirdPartyFile>();
                        var files = Regex.Matches(pluginEdit, @"filename\s?:\s?(""|')(?<file>.*)(""|')");
                        var domFilesMatches = Regex.Matches(pluginEdit, @"SetDOMSideScripts\(\[(?<file>.*)\]\)");
                        var domFileList = new List<string>();
                        var completeFileList = new HashSet<string>();

                        foreach(Match match in domFilesMatches)
                        {
                            var domScripts = match.Groups["file"].ToString().Split(',');
                            foreach(var domScript in domScripts)
                            {
                                var fn = domScript.Trim('"').Trim('\'');
                                domFileList.Add(fn);
                                completeFileList.Add(fn);
                            }
                        }

                        foreach(Match match in files)
                        {
                            var fn = match.Groups["file"].ToString();
                            completeFileList.Add(fn);
                        }

                        foreach (var fn in completeFileList)
                        {
                            var info = new FileInfo(Path.Combine(Path.Combine(tmpPath, fn)));

                            var f = new ThirdPartyFile
                            {
                                Bytes = File.ReadAllBytes(info.FullName),
                                Content = File.ReadAllText(info.FullName),
                                Extention = info.Extension,
                            };

                            switch (info.Extension)
                            {
                                case ".js":
                                    f.Content = FormatHelper.Insatnce.FixMinifiedFiles(f.Content);
                                    f.Compress = true;
                                    f.PlainText = true;
                                    break;
                                case ".html":
                                case ".css":
                                case ".txt":
                                case ".json":
                                case ".xml":
                                    f.PlainText = true;
                                    f.Compress= false;
                                    break;
                                default:
                                    f.Content = $"BINARY FILE => {f.FileName}\nBYTE LENGTH : ({f.Bytes.Length})";
                                    f.PlainText = false;
                                    f.Compress = false;
                                    break;
                            }


                            if (fn.Contains("c3runtime"))
                            {
                                f.C3Folder = true;
                                f.FileName = fn.Replace("c3runtime/", string.Empty).Trim();
                            }
                            else if (fn.Contains("c2runtime"))
                            {
                                f.C2Folder = true;
                                f.FileName = fn.Replace("c2runtime/", string.Empty).Trim();
                            }
                            else
                            {
                                f.Rootfolder = true;
                                f.FileName = fn.Replace("/", "\\").Trim();
                            }

                            foreach(var df in domFileList)
                            {
                                if(df.Contains(f.FileName))
                                {
                                    f.Domfolder = true;
                                }
                            }

                            f.PluginTemplate = TemplateHelper.ThirdPartyFile(f);

                            thirdPartyFiles.Add(f);
                        }

                        //todo: create c3addon, and map parsed data to c3addon 
                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = pluginCat,
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            PluginRunTime = pluginRun,
                            PluginEditTime = pluginEdit,
                            TypeEditTime = typeEdit,
                            TypeRunTime = typeRun,
                            InstanceEditTime = instanceEdit,
                            InstanceRunTime = instanceRun,
                            LanguageProperties = prop,
                            LanguageCategories = cats,
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = pluginType
                        };

                        c3addon.Actions = new Dictionary<string, Action>();
                        c3addon.Conditions = new Dictionary<string, Condition>();
                        c3addon.Expressions = new Dictionary<string, Expression>();

                        foreach (var action in actionList)
                        {
                            c3addon.Actions.Add(action.Id, action);
                        }

                        foreach (var condition in conditionList)
                        {
                            c3addon.Conditions.Add(condition.Id, condition);
                        }

                        foreach (var expression in expressionList)
                        {
                            c3addon.Expressions.Add(expression.Id, expression);
                        }

                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        c3addon.ThirdPartyFiles = new Dictionary<string, ThirdPartyFile>();
                        foreach (var thirdPartyFile in thirdPartyFiles)
                        {
                            c3addon.ThirdPartyFiles.Add($"{thirdPartyFile.ID}", thirdPartyFile);
                        }

                        if (!string.IsNullOrWhiteSpace(c2runtime))
                        {
                            c3addon.C2RunTime = c2runtime;
                        }

                        //regenerate addon file
                        c3addon.AddonJson = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.AddonJson, c3addon);

                        //fixup pluginedit time (replace png iconw ith svg)
                        c3addon.PluginEditTime = Regex.Replace(c3addon.PluginEditTime, @"this._info.SetIcon\(.*\);", "this._info.SetIcon(\"icon.svg\", \"image/svg+xml\");");

                        return c3addon;
                    }
                    else if (type != "effect" && c2Only)
                    {
                        string pluginEdit;

                        pluginEdit = File.ReadAllText(Path.Combine(tmpPath, $"{type}.js"));
                        string typeEdit = File.ReadAllText(Path.Combine(tmpPath, $"type.js"));
                        string instanceEdit = File.ReadAllText(Path.Combine(tmpPath, $"instance.js"));

                        string c2runtime = null;

                        if (Directory.Exists(Path.Combine(tmpPath, "c2runtime")))
                        {
                            c2runtime = File.ReadAllText(Path.Combine(tmpPath, "c2runtime", "runtime.js"));
                        }

                        PluginType pluginType = PluginType.SingleGlobalPlugin;
                        string pluginCat = "other";
                        switch (type)
                        {
                            case "plugin":
                                pluginType = pluginEdit.Contains("SetPluginType(\"world\")")
                                    ? PluginType.DrawingPlugin
                                    : PluginType.SingleGlobalPlugin;
                                pluginCat = Regex.Match(pluginEdit, @"PLUGIN_CATEGORY = ""(?<cat>).*""").Groups["cat"]
                                    .Value;
                                break;
                            case "behavior":
                                pluginType = PluginType.Behavior;
                                pluginCat = Regex.Match(pluginEdit, @"BEHAVIOR_CATEGORY = ""(?<cat>.*)""").Groups["cat"]
                                    .Value;
                                break;
                        }

                        if (string.IsNullOrWhiteSpace(pluginCat)) pluginCat = "other";

                        var ace = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "aces.json")));
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var prop = "\"properties\": " + (string.IsNullOrWhiteSpace(lang["properties"]?.ToString()) ? "{ }" : lang["properties"]);
                        var cats = "\"aceCategories\": " + (string.IsNullOrWhiteSpace(lang["aceCategories"]?.ToString()) ? "{ }" : lang["aceCategories"]);

                        var actionList = new List<Models.Action>();
                        var conditionList = new List<Models.Condition>();
                        var expressionList = new List<Models.Expression>();

                        foreach (JProperty category in ace.Properties())
                        {
                            //parse actions
                            var ationJson = ace[category.Name]["actions"]?.ToString();
                            var actions = ationJson != null ? JArray.Parse(ationJson) : null;
                            if (actions != null)
                            {
                                foreach (var action in actions.Children<JObject>())
                                {
                                    var actionId = action["id"].ToString();
                                    var actionAce = action.ToString();
                                    var actionLang = $"\"{actionId}\":" + lang["actions"][actionId];
                                    var actionScript = action["scriptName"].ToString();
                                    var actionParams = string.Empty;

                                    //only needed for stub methods
                                    if (action["params"] != null && action["params"].Children<JObject>().Any())
                                    {
                                        var ep = action["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        actionParams = string.Join(",", ep);
                                    }

                                    var act = new Models.Action
                                    {
                                        Id = actionId,
                                        Category = category.Name,
                                        Ace = actionAce,
                                        Language = actionLang,
                                        Code = $"{actionScript}({string.Join(",", actionParams)}) {{ \n}}"
                                    };

                                    actionList.Add(act);
                                }
                            }

                            //parse conditions
                            var conditionJson = ace[category.Name]["conditions"]?.ToString();
                            var conditions = conditionJson != null ? JArray.Parse(conditionJson) : null;
                            if (conditions != null)
                            {
                                foreach (var condition in conditions.Children<JObject>())
                                {
                                    var conditionId = condition["id"].ToString();
                                    var conditionAce = condition.ToString();
                                    var conditionLang = $"\"{conditionId}\":" + lang["conditions"][conditionId];
                                    var conditionScript = condition["scriptName"].ToString();
                                    var conditionParams = string.Empty;

                                    //only needed for stub methods
                                    if (condition["params"] != null && condition["params"].Children<JObject>().Any())
                                    {
                                        var ep = condition["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        conditionParams = string.Join(",", ep);
                                    }


                                    var cnd = new Models.Condition()
                                    {
                                        Id = conditionId,
                                        Category = category.Name,
                                        Ace = conditionAce,
                                        Language = conditionLang,
                                        Code = $"{conditionScript}({string.Join(",", conditionParams)}) {{ \n}}"
                                    };

                                    conditionList.Add(cnd);
                                }
                            }

                            //parse expression
                            var expressionJson = ace[category.Name]["expressions"]?.ToString();
                            var expressions = expressionJson != null ? JArray.Parse(expressionJson) : null;
                            if (expressions != null)
                            {
                                foreach (var expression in expressions.Children<JObject>())
                                {
                                    var expressionId = expression["id"].ToString();
                                    var expressionAce = expression.ToString();
                                    var expressionLang = $"\"{expressionId}\":" + lang["expressions"][expressionId];
                                    var expressionScript = expression["expressionName"].ToString();
                                    var expressionParams = string.Empty;

                                    //only needed for stub methods
                                    if (expression["params"] != null && expression["params"].Children<JObject>().Any())
                                    {
                                        var ep = expression["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        expressionParams = string.Join(",", ep);
                                    }

                                    var exp = new Models.Expression()
                                    {
                                        Id = expressionId,
                                        Category = category.Name,
                                        Ace = expressionAce,
                                        Language = expressionLang,
                                        Code = $"{expressionScript}({expressionParams}) {{ \n}}"
                                    };

                                    expressionList.Add(exp);
                                }
                            }
                        }

                        var files = Regex.Matches(pluginEdit, @"filename\s?:\s?(""|')(?<file>.*)(""|')");
                        var thirdPartyFiles = new List<ThirdPartyFile>();
                        foreach (Match match in files)
                        {
                            var fn = match.Groups["file"].ToString();
                            var info = new FileInfo(Path.Combine(Path.Combine(tmpPath, fn)));

                            var f = new ThirdPartyFile
                            {
                                Bytes = null,
                                Content = File.ReadAllText(info.FullName),
                                Extention = info.Extension,
                            };

                            f.PluginTemplate = TemplateHelper.ThirdPartyFile(f);

                            switch (info.Extension)
                            {
                                case ".js":
                                    f.Content = FormatHelper.Insatnce.FixMinifiedFiles(f.Content);
                                    f.Compress = true;
                                    f.PlainText = true;
                                    break;
                                case ".html":
                                case ".css":
                                case ".txt":
                                case ".json":
                                case ".xml":
                                    f.PlainText = true;
                                    f.Compress = false;
                                    break;
                                default:
                                    f.Content = $"BINARY FILE => {f.FileName}\nBYTE LENGTH : ({f.Bytes.Length})";
                                    f.PlainText = false;
                                    f.Compress = false;
                                    break;
                            }

                            if (fn.Contains("c3runtime"))
                            {
                                f.C3Folder = true;
                                f.FileName = fn.Replace("c3runtime/", string.Empty).Trim();
                            }
                            else if (fn.Contains("c2runtime"))
                            {
                                f.C2Folder = true;
                                f.FileName = fn.Replace("c2runtime/", string.Empty).Trim();
                            }
                            else
                            {
                                f.Rootfolder = true;
                                f.FileName = fn.Replace("/", "\\").Trim();
                            }

                            thirdPartyFiles.Add(f);
                        }

                        //todo: create c3addon, and map parsed data to c3addon 
                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = pluginCat,
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            //PluginRunTime = pluginRun,
                            PluginEditTime = pluginEdit,
                            TypeEditTime = typeEdit,
                            //TypeRunTime = typeRun,
                            InstanceEditTime = instanceEdit,
                            //InstanceRunTime = instanceRun,
                            LanguageProperties = prop,
                            LanguageCategories = cats,
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = pluginType
                        };

                        c3addon.Actions = new Dictionary<string, Action>();
                        c3addon.Conditions = new Dictionary<string, Condition>();
                        c3addon.Expressions = new Dictionary<string, Expression>();

                        foreach (var action in actionList)
                        {
                            c3addon.Actions.Add(action.Id, action);
                        }

                        foreach (var condition in conditionList)
                        {
                            c3addon.Conditions.Add(condition.Id, condition);
                        }

                        foreach (var expression in expressionList)
                        {
                            c3addon.Expressions.Add(expression.Id, expression);
                        }

                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        c3addon.ThirdPartyFiles = new Dictionary<string, ThirdPartyFile>();
                        foreach (var thirdPartyFile in thirdPartyFiles)
                        {
                            c3addon.ThirdPartyFiles.Add($"{thirdPartyFile.ID}", thirdPartyFile);
                        }

                        if (!string.IsNullOrWhiteSpace(c2runtime))
                        {
                            c3addon.C2RunTime = c2runtime;
                        }

                        //regenerate template files
                        c3addon.AddonJson = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.AddonJson, c3addon);
                        c3addon.PluginRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.PluginRunTime, c3addon); 
                        c3addon.TypeRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.TypeRunTime, c3addon);
                        c3addon.InstanceRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.InstanceRunTime, c3addon);

                        //fixup pluginedit time (replace png iconw ith svg)
                        c3addon.PluginEditTime = Regex.Replace(c3addon.PluginEditTime, @"this._info.SetIcon\(.*\);", "this._info.SetIcon(\"icon.svg\", \"image/svg+xml\");");

                        return c3addon;
                    }
                    else
                    {
                        //read file text
                        var effectCode = File.ReadAllText(Path.Combine(tmpPath, "effect.fx"));

                        //parse json
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var effect = new Effect();
                        effect.BlendsBackground = addon["blends-background"] != null && addon["blends-background"].ToString().ToLower().Contains("true");
                        effect.CrossSampling = addon["cross-sampling"] != null && addon["cross-sampling"].ToString().ToLower().Contains("true");
                        effect.PreservesOpaqueness = addon["preserves-opaqueness"] != null && addon["preserves-opaqueness"].ToString().ToLower().Contains("true");
                        effect.Animated = addon["animated"] != null && addon["animated"].ToString().ToLower().Contains("true");
                        effect.MustPredraw = addon["must-predraw"] != null && addon["must-predraw"].ToString().ToLower().Contains("true");

                        if (addon["extend-box"] != null)
                        {
                            effect.ExtendBoxVertical = int.Parse(addon["extend-box"]["vertical"].ToString());
                            effect.ExtendBoxHorizontal = int.Parse(addon["extend-box"]["horizontal"].ToString());
                        }
                        
                        //add code fx
                        effect.Code = effectCode;

                        //setup params
                        effect.Parameters = new Dictionary<string, EffectParameter>();
                        foreach (var param in addon["parameters"])
                        {
                            var p = new EffectParameter
                            {
                                Json = param.ToString(formatting: Formatting.Indented),
                                Key = param["id"].ToString()
                            };

                            var l = lang["parameters"][p.Key];
                            p.Lang = $"\"{p.Key}\":" + l;

                            switch (param["type"].ToString())
                            {
                                case "float":
                                case "percent":
                                    p.VariableDeclaration = $"uniform lowp float {p.Key}";
                                    break;
                                case "color":
                                    p.VariableDeclaration = $"uniform lowp vec3 {p.Key}";
                                    break;
                            }   
                            effect.Parameters.Add(p.Key, p);
                        }

                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = addon["category"].ToString(),
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = PluginType.Effect,
                            Effect = effect
                        };

                        //c3 icon
                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");
                        

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        return c3addon;
                    }
                });

            }
             catch (Exception ex)
            {
                LogManager.AddErrorLog(ex);
                LogManager.AddImportLogMessage($"ERROR -> \n{ex.Message}");
                LogManager.AddImportLogMessage($"TRACE -> \n{ex.StackTrace}");
                throw;
            }
            finally
            {
                WindowManager.ShowLoadingOverlay(false);
                var logData = string.Join(Environment.NewLine, LogManager.ImportLog);
                File.WriteAllText(Path.Combine(OptionsManager.CurrentOptions.DataPath, "import.log"), logData);
                LogManager.ImportLog.Clear();
            }

        }

19 View Source File : Steam.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private async Task<List<string>> ReadLibraryPathsAsync()
        {
            var libraryPaths = new List<string>();

            var vdfFile = new FileInfo(Path.Combine(_path, "steamapps", "libraryfolders.vdf"));
            if (!vdfFile.Exists) return libraryPaths;

            string content;
            using var stream = vdfFile.OpenRead();
            using var reader = new StreamReader(stream);
            content = await reader.ReadToEndAsync();

            var matches = Regex.Matches(content, "\"\\d\"\\s+\"(?<path>.+)\"");
            foreach (Match match in matches)
            {
                string path = match.Groups["path"].Value;
                path = path.Replace(@"\\", @"\");
                libraryPaths.Add(path);
            }

            return libraryPaths;
        }

19 View Source File : StringFormattingExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public static string SplitCamelCase(this string value, string delimiter = " ")
        {
            return string.Join(delimiter, Regex.Matches(value, @"(^\p{Ll}+|\p{Lu}+(?!\p{Ll})|\p{Lu}\p{Ll}+)")
                .OfType<Match>()
                .Select(m => m.Value));
        }

19 View Source File : BBCodeDecoder.cs
License : MIT License
Project Creator : atakansarioglu

private static bool ParsePayloadsFromString(string payloadString, out List<string> payloadArray)
        {
            // Check string length.
            if (payloadString.Length > 0)
            {
                // Regexp matcher splits the string by unescaped spaces.
                MatchCollection matchPayloads = Regex.Matches(payloadString, @"((?:(?:[\\]{2})|(?:[\\][ ])|[^\s])*)(?:$|[\s])");

                // Create an array.
                payloadArray = new List<string>(matchPayloads.Count);

                // Preplaced the found payloads to the created array.
                for (int i = 0; i < matchPayloads.Count; i++)
                    payloadArray.Add(UnescapePayloadString(matchPayloads[i].Groups[1].Value));

                // Return success if the payloadString could be parsed.
                return (payloadArray.Count > 0);
            }
            else
            {
                // Return empty array when no payload is present.
                payloadArray = new List<string>();
                return true;
            }
        }

See More Examples