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

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

580 Examples 7

19 View Source File : MainWindow.xaml.Macros.cs
License : MIT License
Project Creator : 3RD-Dimension

private void LoadMacros()
		{
			Macros.Clear();

			var regexMacro = new Regex("([^:;]+):([^:;]+)(:E)?;");

			foreach (System.Text.RegularExpressions.Match m in regexMacro.Matches(Properties.Settings.Default.Macros))
			{
				Macros.Add(new Tuple<string, string, bool>(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Success));
			}

			RefreshMacroButtons();
		}

19 View Source File : Env.cs
License : MIT License
Project Creator : abanu-org

public static string Get(string name)
        {
            var value = Environment.GetEnvironmentVariable(name);
            if (value == null)
            {
                switch (name)
                {
                    case "ABANU_PROJDIR":
                        value = Path.GetDirectoryName(Path.GetDirectoryName(new Uri(typeof(Env).replacedembly.Location).AbsolutePath));
                        if (!File.Exists(Path.Combine(value, "abctl")))
                            value = Path.GetDirectoryName(value);
                        if (!File.Exists(Path.Combine(value, "abctl")))
                            value = Path.GetDirectoryName(value);
                        if (!File.Exists(Path.Combine(value, "abctl")))
                            value = Path.GetDirectoryName(value);
                        if (!File.Exists(Path.Combine(value, "abctl")))
                            value = null;
                        break;
                    case "ABANU_ARCH":
                        value = "x86";
                        break;
                    case "ABANU_BINDIR":
                        value = "${ABANU_PROJDIR}/bin";
                        break;
                    case "ABANU_OSDIR":
                        value = "${ABANU_PROJDIR}/os";
                        break;
                    case "ABANU_NATIVE_FILES":
                        value = "${ABANU_PROJDIR}/bin/${ABANU_ARCH}/Abanu.Native.o";
                        break;
                    case "ABANU_BOOTLOADER_EXE":
                        value = "${ABANU_PROJDIR}/bin/Abanu.OS.Loader.${ABANU_ARCH}.exe";
                        break;
                    case "ABANU_EXE":
                        value = "${ABANU_PROJDIR}/bin/Abanu.OS.Core.${ABANU_ARCH}.exe";
                        break;
                    case "ABANU_LOGDIR":
                        value = "${ABANU_PROJDIR}/logs";
                        break;
                    case "ABANU_ISODIR":
                        value = "${ABANU_PROJDIR}/iso";
                        break;
                    case "ABANU_TOOLSDIR":
                        value = "${ABANU_PROJDIR}/tools";
                        break;
                    case "MOSA_PROJDIR":
                        value = "${ABANU_PROJDIR}/external/MOSA-Project";
                        break;
                    case "MOSA_TOOLSDIR":
                        value = "${MOSA_PROJDIR}/Tools";
                        break;
                    case "qemu":
                        if (Environment.OSVersion.Platform == PlatformID.Unix)
                            value = "qemu-system-x86_64";
                        else
                            value = "${MOSA_TOOLSDIR}/qemu/qemu-system-x86_64.exe";
                        break;
                    case "gdb":
                        value = @"gdb.exe";
                        break;
                    case "nasm":
                        value = "${MOSA_TOOLSDIR}/nasm/nasm.exe";
                        break;
                }

                if (Vars.ContainsKey(name))
                    value = Vars[name];
            }

            var regex = new Regex(@"\$\{(\w+)\}", RegexOptions.RightToLeft);

            if (value == null)
                value = name;

            if (value != null)
                foreach (Match m in regex.Matches(value))
                    value = value.Replace(m.Value, Get(m.Groups[1].Value));
            return value;
        }

19 View Source File : RegexSearchStrategy.cs
License : MIT License
Project Creator : Abdesol

public IEnumerable<ISearchResult> FindAll(ITextSource doreplacedent, int offset, int length)
		{
			int endOffset = offset + length;
			foreach (Match result in searchPattern.Matches(doreplacedent.Text)) {
				int resultEndOffset = result.Length + result.Index;
				if (offset > result.Index || endOffset < resultEndOffset)
					continue;
				if (matchWholeWords && (!IsWordBorder(doreplacedent, result.Index) || !IsWordBorder(doreplacedent, resultEndOffset)))
					continue;
				yield return new SearchResult { StartOffset = result.Index, Length = result.Length, Data = result };
			}
		}

19 View Source File : WordHighlightTagger.cs
License : MIT License
Project Creator : Actipro

public override IEnumerable<TagSnapshotRange<IClreplacedificationTag>> GetTags(NormalizedTextSnapshotRangeCollection snapshotRanges, object parameter) {
			if (String.IsNullOrEmpty(currentWord))
				yield break;

			// Get a regex of the current word
			Regex search = new Regex(String.Format(@"\b{0}\b", currentWord), RegexOptions.Singleline);

			// Loop through the requested snapshot ranges...
			foreach (TextSnapshotRange snapshotRange in snapshotRanges) {
				// If the snapshot range is not zero-length...
				if (!snapshotRange.IsZeroLength) {
					// Look for current word matches
					foreach (Match match in search.Matches(snapshotRange.Text)) {
						// Add a highlighted range
						yield return new TagSnapshotRange<IClreplacedificationTag>(
							new TextSnapshotRange(snapshotRange.Snapshot, TextRange.FromSpan(snapshotRange.StartOffset + match.Index, match.Length)),
							new ClreplacedificationTag(wordHighlightClreplacedificationType)
							);
					}
				}
			}
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void RefreshSquiggleTags() {
			// Get the tagger that was created by the language and has been persisted in the doreplacedent's properties
			//   while the language is active on the doreplacedent
			CustomSquiggleTagger tagger = null;
			if (editor.Doreplacedent.Properties.TryGetValue(typeof(CustomSquiggleTagger), out tagger)) {
				using (var batch = tagger.CreateBatch()) {
					// Clear existing tags
					tagger.Clear();

					// In this example we are going to construct the full snapshot text string... this is not generally a good
					//   idea for a production application since doing so for a large doreplacedent in the UI thread can negatively affect performance...
					//   But this example shows how any text range results (such as those from an external error scan) can be used to generate squiggle tags
					var snapshot = editor.ActiveView.CurrentSnapshot;
					var snapshotText = snapshot.GetText(LineTerminator.Newline);

					// Look for regex pattern matches
					var matches = Regex.Matches(snapshotText, @"\bActipro\b", RegexOptions.IgnoreCase);
					for (var matchIndex = 0; matchIndex < matches.Count; matchIndex++) {
						var match = matches[matchIndex];

						// Create a version range for the match
						var snapshotRange = new TextSnapshotRange(snapshot, TextRange.FromSpan(match.Index, match.Length));
						var versionRange = snapshotRange.ToVersionRange(TextRangeTrackingModes.DeleteWhenZeroLength);
				
						// Create a tag, and include a quick info tip if specified
						var tag = new SquiggleTag();
						tag.ClreplacedificationType = ClreplacedificationTypes.Warning;  // This clreplacedification type is mapped in the tagger to a Green color
						tag.ContentProvider = new PlainTextContentProvider(String.Format("Instance number {0}", matchIndex + 1));

						// Add the tag to the tagger
						tagger.Add(new TagVersionRange<ISquiggleTag>(versionRange, tag));
					}
				}
			}

		}

19 View Source File : Dependencies.cs
License : Apache License 2.0
Project Creator : adamralph

[Fact]
        public static async Task DoubleTransitiveDependency()
        {
            // arrange
            var ran = new List<string>();

            using var outputWriter = new StringWriter();

            var targets = new TargetCollection
            {
                CreateTarget("first", () => ran.Add("first")),
                CreateTarget("second", new[] { "first" }, () => ran.Add("second")),
                CreateTarget("third", new[] { "first", "second" }, () => ran.Add("third")),
            };

            // act
            await targets.RunAsync(new List<string> { "third", "--no-color", "--verbose" }, _ => false, default, outputWriter, Console.Error, false);

            // replacedert
            var output = outputWriter.ToString();

            replacedert.Equal(3, ran.Count);
            replacedert.Equal("first", ran[0]);
            replacedert.Equal("second", ran[1]);
            replacedert.Equal("third", ran[2]);
            _ = replacedert.Single(Regex.Matches(output, "first: Walking dependencies..."));
            _ = replacedert.Single(Regex.Matches(output, "first: Awaiting..."));
        }

19 View Source File : ExternalMembersTests.cs
License : MIT License
Project Creator : adrianoc

[Test] 
        public void Multiple_DllImports_ToSameModule_DoesNotCreate_Multiple_ModuleReferences()
        {   
            var result = RunCecilifier("using System.Runtime.InteropServices; public clreplaced C { [DllImport(\"Bar\")] public static extern int M(); [DllImport(\"Bar\")] public static extern void M2(); }");
            var cecilifiedCode = result.GeneratedCode.ReadToEnd();

            var matches = Regex.Matches(cecilifiedCode, "new PInvokeInfo\\(.+, \".?\", (?<targetModule>.+)\\);").Distinct();
            var moduleReferenceVariableNames = matches.SelectMany(m => m.Groups["targetModule"].Captures).Select(c => c.Value).Distinct();
            replacedert.That(moduleReferenceVariableNames.Count(), Is.EqualTo(1), moduleReferenceVariableNames.Aggregate("Expecting only one ModuleReference instance. Actual:", (acc, curr) => acc + (acc[^1] == ':' ? " " : " ,") + curr));
        }

19 View Source File : ExternalMembersTests.cs
License : MIT License
Project Creator : adrianoc

[Test] 
        public void Multiple_DllImports_ToDifferentModules_DoesNotCreate_Multiple_ModuleReferences()
        {   
            var result = RunCecilifier("using System.Runtime.InteropServices; public clreplaced C { [DllImport(\"Bar\")] public static extern int M(); [DllImport(\"Bar2\")] public static extern void M2(); }");
            var cecilifiedCode = result.GeneratedCode.ReadToEnd();

            var matches = Regex.Matches(cecilifiedCode, "new PInvokeInfo\\(.+, \".?\", (?<targetModule>.+)\\);");
            replacedert.That(matches.Count, Is.EqualTo(2), matches.Aggregate("Actual:", (acc, curr) => acc + (acc[^1] == ':' ? " " : " ,") + curr.Groups["targetModule"].Value));
        }

19 View Source File : PreviewUrlResolver.cs
License : Apache License 2.0
Project Creator : advanced-cms

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

            return virtualPath;
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal static IEnumerable<ulong> GetChannelMentions(DiscordMessage message)
        {
            var regex = new Regex(@"<#(\d+)>", RegexOptions.ECMAScript);
            var matches = regex.Matches(message.Content);
            foreach (Match match in matches)
                yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal static IEnumerable<ulong> GetEmojis(DiscordMessage message)
        {
            var regex = new Regex(@"<a?:([a-zA-Z0-9_]+):(\d+)>", RegexOptions.ECMAScript);
            var matches = regex.Matches(message.Content);
            foreach (Match match in matches)
                yield return ulong.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal static IEnumerable<ulong> GetUserMentions(DiscordMessage message)
        {
            var regex = new Regex(@"<@!?(\d+)>", RegexOptions.ECMAScript);
            var matches = regex.Matches(message.Content);
            foreach (Match match in matches)
                yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal static IEnumerable<ulong> GetRoleMentions(DiscordMessage message)
        {
            var regex = new Regex(@"<@&(\d+)>", RegexOptions.ECMAScript);
            var matches = regex.Matches(message.Content);
            foreach (Match match in matches)
                yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
        }

19 View Source File : PatreonCrawledUrlProcessor.cs
License : MIT License
Project Creator : AlexCSDev

public async Task<bool> ProcessCrawledUrl(ICrawledUrl udpCrawledUrl, string downloadDirectory)
        {
            PatreonCrawledUrl crawledUrl = (PatreonCrawledUrl)udpCrawledUrl;

            bool skipChecks = false; //skip sanitization, duplicate and other checks, do not preplaced filename to download path
            if (crawledUrl.Url.IndexOf("dropbox.com/", StringComparison.Ordinal) != -1)
            {
                if (!crawledUrl.Url.EndsWith("?dl=1"))
                {
                    if (crawledUrl.Url.EndsWith("?dl=0"))
                        crawledUrl.Url = crawledUrl.Url.Replace("?dl=0", "?dl=1");
                    else
                        crawledUrl.Url = $"{crawledUrl.Url}?dl=1";
                }

                _logger.Debug($"[{crawledUrl.PostId}] This is a dropbox entry: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.StartsWith("https://mega.nz/"))
            {
                _logger.Debug($"[{crawledUrl.PostId}] mega found: {crawledUrl.Url}");
                skipChecks = true; //mega plugin expects to see only path to the folder where everything will be saved
            }
            else if (_googleDriveRegex.Match(crawledUrl.Url).Success)
            {
                _logger.Debug($"[{crawledUrl.PostId}] google drive found: {crawledUrl.Url}");
                skipChecks = true; //no need for checks if we use google drive plugin
            }
            else if (crawledUrl.Url.IndexOf("youtube.com/watch?v=", StringComparison.Ordinal) != -1 ||
                     crawledUrl.Url.IndexOf("youtu.be/", StringComparison.Ordinal) != -1)
            {
                //TODO: YOUTUBE SUPPORT?
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] YOUTUBE link found: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.IndexOf("imgur.com/", StringComparison.Ordinal) != -1)
            {
                //TODO: IMGUR SUPPORT
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] IMGUR link found: {crawledUrl.Url}");
            }

            string filename = crawledUrl.Filename;

            if (!skipChecks)
            {
                if (!_patreonDownloaderSettings.UseSubDirectories)
                    filename = $"{crawledUrl.PostId}_";
                else
                    filename = "";

                switch (crawledUrl.UrlType)
                {
                    case PatreonCrawledUrlType.PostFile:
                        filename += "post";
                        break;
                    case PatreonCrawledUrlType.PostAttachment:
                        filename += "attachment";
                        break;
                    case PatreonCrawledUrlType.PostMedia:
                        filename += "media";
                        break;
                    case PatreonCrawledUrlType.AvatarFile:
                        filename += "avatar";
                        break;
                    case PatreonCrawledUrlType.CoverFile:
                        filename += "cover";
                        break;
                    case PatreonCrawledUrlType.ExternalUrl:
                        filename += "external";
                        break;
                    default:
                        throw new ArgumentException($"Invalid url type: {crawledUrl.UrlType}");
                }

                if (crawledUrl.Filename == null)
                {
                    _logger.Debug($"No filename for {crawledUrl.Url}, trying to retrieve...");
                    string remoteFilename =
                        await _remoteFilenameRetriever.RetrieveRemoteFileName(crawledUrl.Url);

                    if (remoteFilename == null)
                    {
                        throw new DownloadException(
                            $"[{crawledUrl.PostId}] Unable to retrieve name for external entry of type {crawledUrl.UrlType}: {crawledUrl.Url}");
                    }

                    filename += $"_{remoteFilename}";
                }
                else
                {
                    filename += $"_{crawledUrl.Filename}";
                }

                _logger.Debug($"Filename for {crawledUrl.Url} is {filename}");

                _logger.Debug($"Sanitizing filename: {filename}");
                filename = PathSanitizer.SanitizePath(filename);
                _logger.Debug($"Sanitized filename: {filename}");

                if (filename.Length > _patreonDownloaderSettings.MaxFilenameLength)
                {
                    _logger.Debug($"Filename is too long, will be truncated: {filename}");
                    string extension = Path.GetExtension(filename);
                    if (extension.Length > 4)
                    {
                        _logger.Warn($"File extension for file {filename} is longer 4 characters and won't be appended to truncated filename!");
                        extension = "";
                    }
                    filename = filename.Substring(0, _patreonDownloaderSettings.MaxFilenameLength) + extension;
                    _logger.Debug($"Truncated filename: {filename}");
                }

                string key = $"{crawledUrl.PostId}_{filename.ToLowerInvariant()}";
                if (!_fileCountDict.ContainsKey(key))
                    _fileCountDict.Add(key, 0);

                _fileCountDict[key]++;

                if (_fileCountDict[key] > 1)
                {
                    _logger.Warn($"Found more than a single file with the name {filename} in the same folder in post {crawledUrl.PostId}, sequential number will be appended to its name.");

                    string appendStr = _fileCountDict[key].ToString();

                    if (crawledUrl.UrlType != PatreonCrawledUrlType.ExternalUrl)
                    {
                        MatchCollection matches = _fileIdRegex.Matches(crawledUrl.Url);

                        if (matches.Count == 0)
                            throw new DownloadException($"[{crawledUrl.PostId}] Unable to retrieve file id for {crawledUrl.Url}, contact developer!");
                        if (matches.Count > 1)
                            throw new DownloadException($"[{crawledUrl.PostId}] More than 1 media found in URL {crawledUrl.Url}");

                        appendStr = matches[0].Groups[5].Value;
                    }

                    filename = $"{Path.GetFileNameWithoutExtension(filename)}_{appendStr}{Path.GetExtension(filename)}";
                }
            }

            if (_patreonDownloaderSettings.UseSubDirectories && 
                crawledUrl.UrlType != PatreonCrawledUrlType.AvatarFile &&
                crawledUrl.UrlType != PatreonCrawledUrlType.CoverFile)
                downloadDirectory = Path.Combine(downloadDirectory, PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, _patreonDownloaderSettings.SubDirectoryPattern));

            crawledUrl.DownloadPath = !skipChecks ? Path.Combine(downloadDirectory, filename) : downloadDirectory + Path.DirectorySeparatorChar;

            return true;
        }

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

void LoadTemplateBody( string guid )
		{
			m_preplacedUniqueIdData.Clear();
			m_guid = guid;
			string datapath = replacedetDatabase.GUIDToreplacedetPath( guid );
			string shaderBody = string.Empty;
			shaderBody = IOUtils.LoadTextFileFromDisk( datapath );
			shaderBody = shaderBody.Replace( "\r\n", "\n" );

			// Insert Before Tag
			MatchCollection col = Regex.Matches( shaderBody, TemplateHelperFunctions.BeforePragmaPattern, RegexOptions.Singleline );
			for( int i = col.Count - 1; i >= 0; i-- )
			{
				if( col[ i ].Groups.Count == 3 )
				{
					shaderBody = shaderBody.Insert( col[ i ].Groups[ 2 ].Index, TemplatesManager.TemplatePragmaBeforeTag + "\n" + col[ i ].Groups[ 1 ].Value );
				}
			}

			m_shaderData = TemplateShaderInfoUtil.CreateShaderData( shaderBody );
			if( m_shaderData == null )
			{
				m_isValid = false;
				return;
			}

			m_templateIdManager = new TemplateIdManager( shaderBody );

			try
			{
				int nameBegin = shaderBody.IndexOf( TemplatesManager.TemplateShaderNameBeginTag );
				if( nameBegin < 0 )
				{
					// Not a template
					return;
				}

				int nameEnd = shaderBody.IndexOf( TemplatesManager.TemplateFullEndTag, nameBegin );
				if( nameEnd < 0 )
					return;

				
				m_shaderBody = shaderBody;
				int defaultBegin = nameBegin + TemplatesManager.TemplateShaderNameBeginTag.Length;
				int defaultLength = nameEnd - defaultBegin;
				m_defaultShaderName = shaderBody.Substring( defaultBegin, defaultLength );
				int[] nameIdx = m_defaultShaderName.AllIndexesOf( "\"" );
				nameIdx[ 0 ] += 1; // Ignore the " character from the string
				m_defaultShaderName = m_defaultShaderName.Substring( nameIdx[ 0 ], nameIdx[ 1 ] - nameIdx[ 0 ] );
				m_shaderNameId = shaderBody.Substring( nameBegin, nameEnd + TemplatesManager.TemplateFullEndTag.Length - nameBegin );
				m_templateProperties.AddId( shaderBody, m_shaderNameId, false );
				m_templateIdManager.RegisterId( nameBegin, m_shaderNameId, m_shaderNameId );
				shaderBody = shaderBody.Substring( nameEnd + TemplatesManager.TemplateFullEndTag.Length );
			}
			catch( Exception e )
			{
				Debug.LogException( e );
				m_isValid = false;
			}

			m_customTemplatePropertyUI = TemplateHelperFunctions.FetchCustomUI( shaderBody );
			TemplateHelperFunctions.FetchDependencies( m_dependenciesContainer, ref m_shaderBody );
			if( m_dependenciesContainer.IsValid )
			{
				int index = m_dependenciesContainer.Id.IndexOf( TemplatesManager.TemplateDependenciesListTag );
				m_templateProperties.AddId( new TemplateProperty( m_dependenciesContainer.Id, m_dependenciesContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_dependenciesContainer.Index, m_dependenciesContainer.Id, m_dependenciesContainer.Id );
			}

			TemplateHelperFunctions.FetchCustomInspector( m_customInspectorContainer, ref m_shaderBody );
			if( m_customInspectorContainer.IsValid )
			{
				int index = m_customInspectorContainer.Id.IndexOf( "CustomEditor" );
				m_templateProperties.AddId( new TemplateProperty( m_customInspectorContainer.Id, m_customInspectorContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_customInspectorContainer.Index, m_customInspectorContainer.Id, m_customInspectorContainer.Id );
			}

			TemplateHelperFunctions.FetchFallback( m_fallbackContainer, ref m_shaderBody );
			if( m_fallbackContainer.IsValid )
			{
				int index = m_fallbackContainer.Id.IndexOf( "Fallback",StringComparison.InvariantCultureIgnoreCase );
				m_templateProperties.AddId( new TemplateProperty( m_fallbackContainer.Id, m_fallbackContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_fallbackContainer.Index, m_fallbackContainer.Id, m_fallbackContainer.Id );
			}
			// Shader body may have been changed to inject inexisting tags like fallback
			m_templateIdManager.ShaderBody = m_shaderBody;

			m_propertyTag = new TemplateTagData( m_shaderData.PropertyStartIdx, TemplatesManager.TemplatePropertyTag, true );
			m_templateIdManager.RegisterId( m_shaderData.PropertyStartIdx, TemplatesManager.TemplatePropertyTag, TemplatesManager.TemplatePropertyTag );
			m_templateProperties.AddId( shaderBody, TemplatesManager.TemplatePropertyTag, true );
			Dictionary<string, TemplateShaderPropertyData> duplicatesHelper = new Dictionary<string, TemplateShaderPropertyData>();
			TemplateHelperFunctions.CreateShaderPropertiesList( m_shaderData.Properties, ref m_availableShaderProperties, ref duplicatesHelper );
			int subShaderCount = m_shaderData.SubShaders.Count;

			int mainSubShaderIdx = -1;
			int mainPreplacedIdx = -1;

			int firstVisibleSubShaderId = -1;
			int firstVisiblePreplacedId = -1;
			bool foundMainPreplaced = false;
			bool foundFirstVisible = false;

			m_templateIdManager.RegisterTag( TemplatesManager.TemplatePreplacedesEndTag );
			m_templateIdManager.RegisterTag( TemplatesManager.TemplateMainPreplacedTag );

			for( int i = 0; i < subShaderCount; i++ )
			{
				TemplateSubShader subShader = new TemplateSubShader( i, m_templateIdManager, "SubShader" + i, m_shaderData.SubShaders[ i ], ref duplicatesHelper );

				if( subShader.FoundMainPreplaced )
				{
					if( !foundMainPreplaced )
					{
						foundMainPreplaced = true;
						mainSubShaderIdx = i;
						mainPreplacedIdx = subShader.MainPreplaced;
					}
				}
				else if( subShader.MainPreplaced > -1 )
				{
					if( !foundFirstVisible )
					{
						foundFirstVisible = true;
						firstVisibleSubShaderId = i;
						firstVisiblePreplacedId = subShader.MainPreplaced;
					}
				}

				m_subShaders.Add( subShader );
				m_masterNodesRequired += subShader.Preplacedes.Count;
			}


			if( !foundMainPreplaced && foundFirstVisible )
			{
				mainSubShaderIdx = firstVisibleSubShaderId;
				mainPreplacedIdx = firstVisiblePreplacedId;
			}

			for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
			{
				int preplacedCount = m_subShaders[ subShaderIdx ].Preplacedes.Count;
				for( int preplacedIdx = 0; preplacedIdx < preplacedCount; preplacedIdx++ )
				{
					m_subShaders[ subShaderIdx ].Preplacedes[ preplacedIdx ].IsMainPreplaced = ( mainSubShaderIdx == subShaderIdx && mainPreplacedIdx == preplacedIdx );
				}
			}

			duplicatesHelper.Clear();
			duplicatesHelper = null;
			m_isSinglePreplaced = ( m_subShaders.Count == 1 && m_subShaders[ 0 ].PreplacedAmount == 1 );
			
		}

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 : MarkdownExportTests.cs
License : GNU General Public License v3.0
Project Creator : alxnbl

[Test]
        public override void Image_SimpleImage()
        {
            var res = TestHelper.RunExporter("1", "TestBloc", "Image", "Simple image");


            // http://regexstorm.net/tester
            string regexImgAttributes = "!\\[.*\\]\\((?<path>\\.\\./_resources/)(?<filename>.*)\\)";

            MatchCollection matchs = Regex.Matches(res.exportResult, regexImgAttributes, RegexOptions.IgnoreCase);

            var folderPath = matchs[0].Groups["path"].Value;
            var fileName = matchs[0].Groups["filename"].Value;

            replacedert.AreEqual("../_resources/", folderPath);
            replacedert.IsTrue(File.Exists(Path.Combine("TestBloc", "Image", folderPath + fileName)));
        }

19 View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich

private bool ContainsResourceDictionary(ReloadItem item, string dictName, string[] nameParts)
        {
            var isCss = Path.GetExtension(dictName) == ".css";
            var element = item.Objects.FirstOrDefault() as VisualElement;
            var matches = Regex.Matches(item.Xaml.InnerXml, @"Source[\s]*=[\s]*""([^""]+\.(xaml|css))""", RegexOptions.Compiled);
            foreach (Match match in matches)
            {
                var value = match.Groups[1].Value;
                var resId = GetResId(new Uri(value, UriKind.Relative), element ?? (object)App);
                if (dictName.EndsWith(resId, StringComparison.Ordinal))
                {
                    return true;
                }
                if (isCss)
                {
                    continue;
                }
                var checkItem = GereplacedemForReloadingSourceRes(new Uri(value, UriKind.Relative), element ?? (object)App);
                if (checkItem != null)
                {
                    return true;
                }
            }

            if (nameParts?.Any() ?? false)
            {
                var nameSpace = string.Join("\\.", nameParts.Take(nameParts.Length - 1));

                if (Regex.IsMatch(item.Xaml.InnerXml, $"[\\s]*=[\\s]*\\\".+({nameSpace})\\\"\\s", RegexOptions.Compiled) &&
                   Regex.IsMatch(item.Xaml.InnerXml, $"[\\s]*\\:[\\s]*{nameParts.Last()}"))
                {
                    return true;
                }
            }

            return GetResourceDictionaries(element?.Resources).Any(x => x.GetType().FullName == dictName);
        }

19 View Source File : DockerMonitor.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7

private String GetHostDirectory(String source) {
            MatchCollection matches = m_SourceToHostPath.Matches(source);
            if (matches.Count != 1 || matches[0].Groups.Count != 3) { return null; }
            return $"{matches[0].Groups[1]}:\\{matches[0].Groups[2]}";
        }

19 View Source File : FixUriService.cs
License : MIT License
Project Creator : anjoy8

public void FixBaskereplacedemPictureUri(IEnumerable<Baskereplacedem> baskereplacedems)
        {
            if (baskereplacedems == null)
            {
                return;
            }

            try
            {
                if (!ViewModelLocator.UseMockService
                    && _settingsService.IdenreplacedyEndpointBase != GlobalSetting.DefaultEndpoint)
                {
                    foreach (var baskereplacedem in baskereplacedems)
                    {
                        MatchCollection serverResult = IpRegex.Matches(baskereplacedem.PictureUrl);
                        MatchCollection localResult = IpRegex.Matches(_settingsService.IdenreplacedyEndpointBase);

                        if (serverResult.Count != -1 && localResult.Count != -1)
                        {
                            var serviceIp = serverResult[0].Value;
                            var localIp = localResult[0].Value;
                            baskereplacedem.PictureUrl = baskereplacedem.PictureUrl.Replace(serviceIp, localIp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

19 View Source File : FixUriService.cs
License : MIT License
Project Creator : anjoy8

public void FixCampaignItemPictureUri(IEnumerable<CampaignItem> campaignItems)
        {
            if (campaignItems == null)
            {
                return;
            }

            try
            {
                if (!ViewModelLocator.UseMockService
                    && _settingsService.IdenreplacedyEndpointBase != GlobalSetting.DefaultEndpoint)
                {
                    foreach (var campaignItem in campaignItems)
                    {
                        MatchCollection serverResult = IpRegex.Matches(campaignItem.PictureUri);
                        MatchCollection localResult = IpRegex.Matches(_settingsService.IdenreplacedyEndpointBase);

                        if (serverResult.Count != -1 && localResult.Count != -1)
                        {
                            var serviceIp = serverResult[0].Value;
                            var localIp = localResult[0].Value;

                            campaignItem.PictureUri = campaignItem.PictureUri.Replace(serviceIp, localIp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

19 View Source File : FixUriService.cs
License : MIT License
Project Creator : anjoy8

public void FixCatalogItemPictureUri(IEnumerable<CatalogItem> catalogItems)
        {
            if (catalogItems == null)
            {
                return;
            }

            try
            {
                if (!ViewModelLocator.UseMockService
                    && _settingsService.IdenreplacedyEndpointBase != GlobalSetting.DefaultEndpoint)
                {
                    foreach (var catalogItem in catalogItems)
                    {
                        MatchCollection serverResult = IpRegex.Matches(catalogItem.PictureUri);
                        MatchCollection localResult = IpRegex.Matches(_settingsService.IdenreplacedyEndpointBase);

                        if (serverResult.Count != -1 && localResult.Count != -1)
                        {
                            var serviceIp = serverResult[0].Value;
                            var localIp = localResult[0].Value;

                            catalogItem.PictureUri = catalogItem.PictureUri.Replace(serviceIp, localIp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

19 View Source File : KanjiView.xaml.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private List<Geometry> GetSvgPaths()
        {
            var matches = pathRegex.Matches(kanji.SVGData);
            List<Geometry> paths = new List<Geometry>(matches.Count);
            foreach (Match match in matches)
            {
                foreach (Match matchData in dataRegex.Matches(match.Value))
                {
                    string data = matchData.Value.Trim();
                    data = data.Substring(3, matchData.Value.Length - 5);
                    paths.Add(Geometry.Parse(data));
                }
            }
            return paths;
        }

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

private static void CreateRubySections(replacedLine line)
        {
            for (int sectionIdx = line.Sections.Count - 1; sectionIdx >= 0; sectionIdx--)
            {
                replacedSection section = (replacedSection)line.Sections[sectionIdx];
                if (section.RubyPosition == RubyPosition.None)
                    continue;

                MatchCollection matches = Regex.Matches(section.Text, @"\[(?<text>.+?)/(?<ruby>.+?)\]");
                if (matches.Count == 0)
                    continue;

                line.Sections.RemoveAt(sectionIdx);

                int interStartPos = 0;
                int numSubSections = 0;
                foreach (Match match in matches)
                {
                    if (match.Index > interStartPos)
                        InsertRubySection(line, section, section.Text.Substring(interStartPos, match.Index - interStartPos), RubyPart.None, sectionIdx, ref numSubSections);

                    InsertRubySection(line, section, match.Groups["text"].Value, RubyPart.Text, sectionIdx, ref numSubSections);
                    InsertRubySection(line, section, "(", RubyPart.Parenthesis, sectionIdx, ref numSubSections);
                    InsertRubySection(line, section, match.Groups["ruby"].Value, section.RubyPosition == RubyPosition.Below ? RubyPart.RubyBelow : RubyPart.RubyAbove, sectionIdx, ref numSubSections);
                    InsertRubySection(line, section, ")", RubyPart.Parenthesis, sectionIdx, ref numSubSections);

                    interStartPos = match.Index + match.Length;
                }

                if (interStartPos < section.Text.Length)
                    InsertRubySection(line, section, section.Text.Substring(interStartPos), RubyPart.None, sectionIdx, ref numSubSections);

                ((replacedSection)line.Sections[sectionIdx]).Duration = section.Duration;
            }
        }

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

public override void ViewDidAppear()
        {
            base.ViewDidAppear();

            ((View)View).Controller = this;
            View.RegisterForDraggedTypes(new[] { NSPasteboard.NSPasteboardTypeFileUrl.ToString() });

            Version version = replacedembly.GetEntryreplacedembly().GetName().Version;
            View.Window.replacedle = $"YTSubConverter {version.Major}.{version.Minor}.{version.Build}";

            Application.OpenMenuItem.Activated += (s, e) => _btnBrowse_Click(null);
            Application.ConvertMenuItem.Activated += (s, e) => _btnConvert_Click(null);
            Application.AutoconvertMenuItem.Activated += (s, e) => _chkAutoConvert.SetChecked(!_chkAutoConvert.IsChecked());

            _dlgOpenSubreplacedles = NSOpenPanel.OpenPanel;
            _dlgOpenSubreplacedles.CanChooseDirectories = false;
            _dlgOpenSubreplacedles.AllowsMultipleSelection = false;

            _dlgOpenSubreplacedles.AllowedFileTypes = Regex.Matches(Shared.Resources.SubreplacedleFileFilter, @"\*\.(\w+)")
                                                      .Cast<Match>()
                                                      .Select(m => m.Groups[1].Value)
                                                      .ToArray();

            _subreplacedleRenameWatcher = new FileSystemWatcher { NotifyFilter = NotifyFilters.FileName };
            _subreplacedleRenameWatcher.Renamed += HandleTmpFileRenamed;

            _subreplacedleModifyWatcher = new FileSystemWatcher { NotifyFilter = NotifyFilters.LastWrite };
            _subreplacedleModifyWatcher.Changed += HandleFileModified;

            _lstStyles.FocusRingType = NSFocusRingType.None;
            _lstStyles.SelectionDidChange += _lstStyles_SelectedIndexChanged;

            LocalizeUI();
            ClearUi();
        }

19 View Source File : SyntaxHighlighting.cs
License : GNU General Public License v3.0
Project Creator : arklumpus

private string HighlightUsingRegex(Definition definition, string input)
        {
            var regexOptions = GetRegexOptions(definition);
            var evaluator = GetMatchEvaluator(definition);
            var regexPattern = definition.GetRegexPattern();

            int currentIndex = 0;

            foreach (Match match in Regex.Matches(input, regexPattern))
            {
                if (match.Index > currentIndex)
                {
                    this.HighlightedSpans.Add(new FormattedString(input.Substring(currentIndex, match.Index - currentIndex), Colours.Black, false, false));
                }

                currentIndex = match.Index + match.Length;

                evaluator(match);
            }

            if (currentIndex < input.Length)
            {
                this.HighlightedSpans.Add(new FormattedString(input.Substring(currentIndex, input.Length - currentIndex), Colours.Black, false, false));
            }

            return null;
        }

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

private bool ValidateFiles(C3Addon addon)
        {
            if (addon.Type == PluginType.Effect)
            {
                if (!AddonValidator.Insatnce.Validate(addon))
                {
                    return false;
                }
            }
            else if (addon.Type == PluginType.Theme)
            {
                //todo: validate css
            }
            else
            {
                if (string.IsNullOrWhiteSpace(addon.LanguageProperties))
                {
                    LogManager.CompilerLog.Insert("generate properties json has not been ran, generate the json in the langauge view");
                    return false;
                }
                if (string.IsNullOrWhiteSpace(addon.LanguageCategories))
                {
                    LogManager.CompilerLog.Insert("generate category json has not been ran, generate the json in the langauge view");
                    return false;
                }

                var placeholder = new Regex("{(\\d+)}|{\\.\\.\\.}");
                var dpPlaceholder = new Regex("\"display-text\":.*");

                foreach (var action in addon.Actions)
                {
                    var paramCount = action.Value.Ace.Count(x => x == '{') - 1;
                    var displayText = dpPlaceholder.Matches(action.Value.Language)[0].Value;

                    var displayCount = placeholder.Matches(string.IsNullOrWhiteSpace(displayText) ? action.Value.Language : displayText).Count;

                    if (paramCount != displayCount)
                    {
                        LogManager.CompilerLog.Insert($"invalid amount of parameter placeholder in display text for {action.Value.Id}, {paramCount} parameters expected {displayCount} placeholders {{#}} in display text");
                        return false;
                    }
                }

                foreach (var condition in addon.Conditions)
                {
                    var paramCount = condition.Value.Ace.Count(x => x == '{') - 1;
                    var displayCount = placeholder.Matches(condition.Value.Language).Count;

                    if (paramCount != displayCount)
                    {
                        LogManager.CompilerLog.Insert($"invalid amount parameter placeholder in display text for {condition.Value.Id}, {paramCount} parameters expected {displayCount} placeholders {{#}} in display text");
                        return false;
                    }
                }
            }
           
            return true;
        }

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

private void AddPropertyButton_Click(object sender, RoutedEventArgs e)
        {
            var id = PropertyIdText.Text.Replace(" ", "-");
            var type = PropertyTypeDropdown.Text;
            var timelineCheck = PropertyTimeLineSupport.IsChecked.HasValue && PropertyTimeLineSupport.IsChecked.Value;
            string template;

            //check for duplicate property id
            var propertyRegex = new Regex(@"\n?\t?\t?\t?\t?new SDK[.]PluginProperty\(\""(?<type>\w+)\"",(\s|\"")+(?<id>(\w|[-])+)\"",.*\)[,]?");
            var propertyMatches = propertyRegex.Matches(EditTimePluginTextEditor.Text);

            foreach (Match propertyMatch in propertyMatches)
            {
                if (propertyMatch.Groups["id"].ToString() == id)
                {
                    NotificationManager.PublishErrorNotification("cannot have duplicate property id.");
                    return;
                }
            }

            //removed existing properties
            EditTimePluginTextEditor.Text = propertyRegex.Replace(EditTimePluginTextEditor.Text, string.Empty);


            var timelineSupport = timelineCheck ? "true" : "false";
            //get template
            switch (type)
            {
                case "integer":
                case "float":
                case "percent":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", 0, {{\"interpolatable\":{timelineSupport}}})";
                    break;

                case "text":
                case "longtext":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", \"value\", {{\"interpolatable\":{timelineSupport}}})";
                    break;

                case "check":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", true, {{\"interpolatable\":{timelineSupport}}})";
                    break;

                case "color":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", {{\"initialValue\": [1,0,0], \"interpolatable\":{timelineSupport}}} )";
                    break;

                case "combo":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", {{\"items\":[\"item1\", \"item2\", \"item3\"], \"initialValue\": \"item1\", \"interpolatable\":{timelineSupport}}})";
                    break;

                case "group":
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"value\")";
                    break;

                default:
                    template = $"\n\t\t\t\tnew SDK.PluginProperty(\"{type}\", \"{id}\", \"value\")";
                    break;
            }

            var propList = new List<string>();
            foreach (Match propertyMatch in propertyMatches)
            {
                propList.Add($"{propertyMatch.Value.TrimEnd(',')}");
            }
            propList.Add(template);

            EditTimePluginTextEditor.Text = EditTimePluginTextEditor.Text.Replace("this._info.SetProperties([", $"this._info.SetProperties([{string.Join(",", propList)}");
            NewPropertyWindow.IsOpen = false;
        }

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

public static ISegment GetCurrentWord(this TextArea textArea)
        {
            DoreplacedentLine line = textArea.Doreplacedent.GetLineByNumber(textArea.Caret.Line);

            if (line.Length == 0)
                return null;

            int lineCaretPosition = textArea.Caret.Offset - line.Offset;

            int startOffset = -1;
            int length = -1;

            MatchCollection matches = _wordRegex.Matches(textArea.Doreplacedent.GetText(line));
            foreach (Match match in matches)
            {
                //TODO: just return word not segment, see the impact of returning string here
                if (match.Index <= lineCaretPosition && (match.Index + match.Length) >= lineCaretPosition)
                {
                    startOffset = line.Offset + match.Index;
                    length = match.Length;
                    break;
                }
            }

            if (startOffset != -1)
                return new AnchorSegment(textArea.Doreplacedent, startOffset, length);

            return null;
        }

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

public static string GetPreviousWord(this TextArea textArea)
        {
            DoreplacedentLine line = textArea.Doreplacedent.GetLineByNumber(textArea.Caret.Line);

            if (line.Length == 0)
                return null;

            MatchCollection matches = _previousWordRegx.Matches(textArea.Doreplacedent.GetText(line)); int lineCaretPosition = textArea.Caret.Offset - line.Offset;
            foreach (Match match in matches)
            {
                var previousStatement = Regex.Replace(match.Captures[0].ToString(), @"\t|\n|\r", "");
                var statementArray = previousStatement.Split(new [] {"."}, StringSplitOptions.RemoveEmptyEntries);
                return statementArray[statementArray.Length - 1];
            }

            return null;
        }

19 View Source File : TextHelper.cs
License : Apache License 2.0
Project Creator : artemshuba

public static void ParseHashtags(Paragraph paragraph, UnderlineStyle underlineStyle = UnderlineStyle.None)
        {
            int i = 0;

            while (i < paragraph.Inlines.Count)
            {
                var inline = paragraph.Inlines[i];
                if (!(inline is Run))
                {
                    i++;
                    continue;
                }

                var content = ((Run)inline).Text;

                var regex = _hashtagsRegex;

                var matches = regex.Matches(content);

                if (matches.Count > 0)
                {

                    int index = 0;


                    foreach (Match match in matches)
                    {
                        paragraph.Inlines.Remove(inline);

                        int matchIndex = match.Index;

                        //Add text before link.
                        var beforeText = content.Substring(index, matchIndex - index);
                        var run = new Run() { Text = beforeText };
                        paragraph.Inlines.Insert(i, run);

                        i++;

                        // Add link.
                        string linkString = match.Value;

                        var hyperlink = new Hyperlink();
                        hyperlink.UnderlineStyle = underlineStyle;
                        run = new Run() { Text = linkString };
                        hyperlink.Inlines.Add(run);

                        // Complete link if necessary.
                        linkString = $"https://vk.com/feed?section=search&q={linkString}";

                        if (Uri.IsWellFormedUriString(linkString, UriKind.Absolute))
                        {
                            hyperlink.NavigateUri = new Uri(linkString);
                            paragraph.Inlines.Insert(i, hyperlink);

                            index = matchIndex + match.Length;

                            i++;
                        }
                    }

                    //Add text after all links.
                    var afterText = content.Substring(index, content.Length - index);
                    var afterRun = new Run() { Text = afterText };
                    paragraph.Inlines.Insert(i, afterRun);
                }

                i++;
            }
        }

19 View Source File : TextHelper.cs
License : Apache License 2.0
Project Creator : artemshuba

public static void ParseInternalLinks(Paragraph paragraph, UnderlineStyle underlineStyle = UnderlineStyle.None)
        {
            int i = 0;

            while (i < paragraph.Inlines.Count)
            {
                var inline = paragraph.Inlines[i];
                if (!(inline is Run))
                {
                    i++;
                    continue;
                }

                var content = ((Run)inline).Text;

                var regex = _internalLinksRegex;

                var matches = regex.Matches(content);

                if (matches.Count > 0)
                {
                    int index = 0;

                    foreach (Match match in matches)
                    {
                        paragraph.Inlines.Remove(inline);

                        int matchIndex = match.Index;

                        //Add text before link.
                        var beforeText = content.Substring(index, matchIndex - index);
                        var run = new Run() { Text = beforeText };
                        paragraph.Inlines.Insert(i, run);

                        i++;

                        // Add link.
                        string linkString = match.Value.Trim(new char[] { '[', ']' });
                        string replacedle = linkString;

                        if (linkString.Contains("|"))
                        {
                            replacedle = linkString.Substring(linkString.IndexOf("|") + 1);
                            linkString = linkString.Substring(0, linkString.Length - replacedle.Length - 1);
                        }

                        var hyperlink = new Hyperlink();
                        hyperlink.UnderlineStyle = underlineStyle;
                        run = new Run() { Text = replacedle };
                        hyperlink.Inlines.Add(run);

                        // Complete link if necessary.
                        linkString = $"https://vk.com/{linkString}";

                        if (Uri.IsWellFormedUriString(linkString, UriKind.Absolute))
                        {
                            hyperlink.NavigateUri = new Uri(linkString);
                            paragraph.Inlines.Insert(i, hyperlink);

                            index = matchIndex + match.Length;

                            i++;
                        }
                    }

                    //Add text after all links.
                    var afterText = content.Substring(index, content.Length - index);
                    var afterRun = new Run() { Text = afterText };
                    paragraph.Inlines.Insert(i, afterRun);
                }

                i++;
            }
        }

19 View Source File : SetupDialogForm.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

private void AddressList_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool isValid = false;

            if (IsIpAddress(addressList.Text)) // The host name is an IP address so test whether this is valid
            {
                MatchCollection matches = validIpAddressRegex.Matches(addressList.Text);
                if (matches.Count == 0)
                {
                    SetupErrorProvider.SetError(addressList, "IP addresses can only contain digits and the point character in the form WWW.XXX.YYY.ZZZ.");
                }
                else
                {
                    isValid = true;
                }
            }
            else // The host name is a string rather than an IP address so validate this
            {
                MatchCollection matches = validHostnameRegex.Matches(addressList.Text);
                if (matches.Count == 0)
                {
                    SetupErrorProvider.SetError(addressList, "Not a valid host name.");
                }
                else
                {
                    isValid = true;
                }
            }

            if (isValid)
            {
                SetupErrorProvider.Clear();
                btnOK.Enabled = true;
            }
            else
            {
                btnOK.Enabled = false;
            }

        }

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

public async Task<List<int>> GetPostIds(string cafeId, string boardId, CancellationToken ct)
        {
            var response = await _client.GetAsync($"https://m.cafe.daum.net/{cafeId}/{boardId}", ct);
            var result = new List<int>();

            if (!response.IsSuccessStatusCode)
                return result;

            var content = await response.Content.ReadreplacedtringAsync();
            foreach (Match match in Regex.Matches(content, $"{cafeId}/{boardId}/([0-9]+)[\"\\/]"))
            {
                if (match.Groups.Count < 2)
                    continue;

                int id;
                if (!int.TryParse(match.Groups[1].Value, out id))
                    continue;

                result.Add(id);
            }

            return result;
        }

19 View Source File : RegexSearchStrategy.cs
License : MIT License
Project Creator : AvaloniaUI

public IEnumerable<ISearchResult> FindAll(ITextSource doreplacedent, int offset, int length)
		{
			int endOffset = offset + length;
			foreach (Match result in _searchPattern.Matches(doreplacedent.Text)) {
				int resultEndOffset = result.Length + result.Index;
				if (offset > result.Index || endOffset < resultEndOffset)
					continue;
				if (_matchWholeWords && (!IsWordBorder(doreplacedent, result.Index) || !IsWordBorder(doreplacedent, resultEndOffset)))
					continue;
				yield return new SearchResult { StartOffset = result.Index, Length = result.Length, Data = result };
			}
		}

19 View Source File : CodeGenConsole.cs
License : MIT License
Project Creator : Avanade

public Task<int> RunAsync(string? args = null)
        {
            if (string.IsNullOrEmpty(args))
                return RunAsync(Array.Empty<string>());

            // See for inspiration: https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c-sharp/298990#298990
            var regex = Regex.Matches(args, @"\G(""((""""|[^""])+)""|(\S+)) *");
            var array = regex.Cast<Match>()
                         .Select(m => Regex.Replace(
                             m.Groups[2].Success
                                 ? m.Groups[2].Value
                                 : m.Groups[4].Value, @"""""", @"""")).ToArray();

            return RunAsync(array);
        }

19 View Source File : AbstractApiWrapper.cs
License : MIT License
Project Creator : Avanade

internal async Task<HttpResponseMessage> ResilientRequest(string URL, HttpClient httpClient, WorkBenchServiceHttp http, ByteArrayContent data = null)
        {
            if (_stub)
            {
                var config = new MockData().GetMockData<StubAPIConfiguration>("stubAPIData");
                if (config != null)
                {
                    HostStubAPIConfiguration host = config.Hosts.Where(x => x.Name == _apiname).FirstOrDefault();
                    if (host != null)
                    {
                        MethodStubAPIConfiguration method = host.Methods.Where(x => x.WorkBenchServiceHttp == http
                                                                              && Regex.Matches(URL, x.Route, RegexOptions.IgnoreCase).FirstOrDefault() != null
                        ).FirstOrDefault();

                        string jsonString = (new { PayLoad = method.Response, critics = new List<Critic>() }).ToStringCamelCase();
                        return await Task.FromResult(new HttpResponseMessage()
                        {
                            StatusCode = HttpStatusCode.OK,
                            Content = new StringContent(jsonString, System.Text.Encoding.UTF8),

                        });
                    }
                    else
                    {
                        throw new LightException($"Workbench cannot made the request for: {URL} by STUB, there isn't host for request.");
                    }
                }
                else
                {
                    throw new LightException($"Workbench cannot made the request for: {URL} by STUB, check the configuration file.");
                }
            }
            else
            {
                if (this.Polly != null)
                {
                    return await this.Polly.ResilientRequest(URL, httpClient, http, LightConfigurator.Config<ApiConfiguration>(this._apiname).Polly, data);
                }
                else
                {
                    switch (http)
                    {
                        case WorkBenchServiceHttp.GET:
                            return await httpClient.GetAsync(URL);
                        case WorkBenchServiceHttp.POST:
                            return await httpClient.PostAsync(URL, data);
                        case WorkBenchServiceHttp.PUT:
                            return await httpClient.PutAsync(URL, data);
                        case WorkBenchServiceHttp.DELETE:
                            return await httpClient.DeleteAsync(URL);
                        default:
                            throw new LightException($"Workbench cannot made the request for: {URL}");
                    }
                }
            }
        }

19 View Source File : DatabaseConsole.cs
License : MIT License
Project Creator : Avanade

public Task<int> RunAsync(string? args = null)
        {
            if (string.IsNullOrEmpty(args))
                return RunAsync(Array.Empty<string>());

            // See for inspiration: https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c-sharp/298990#298990
            var regex = Regex.Matches(args, @"\G(""((""""|[^""])+)""|(\S+)) *");
            var array = regex.Cast<Match>()
                .Select(m => Regex.Replace(
                    m.Groups[2].Success
                        ? m.Groups[2].Value
                        : m.Groups[4].Value, @"""""", @"""")).ToArray();

            return RunAsync(array);
        }

19 View Source File : BlogController.cs
License : Apache License 2.0
Project Creator : aws

private async Task SaveFilesToDisk(Post post)
        {
            var imgRegex = new Regex("<img[^>]+ />", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var base64Regex = new Regex("data:[^/]+/(?<ext>[a-z]+);base64,(?<base64>.+)", RegexOptions.IgnoreCase);
            var allowedExtensions = new[] {
              ".jpg",
              ".jpeg",
              ".gif",
              ".png",
              ".webp"
            };

            foreach (Match? match in imgRegex.Matches(post.Content))
            {
                if (match is null)
                {
                    continue;
                }

                var doc = new XmlDoreplacedent();
                doc.LoadXml($"<root>{match.Value}</root>");

                var img = doc.FirstChild.FirstChild;
                var srcNode = img.Attributes["src"];
                var fileNameNode = img.Attributes["data-filename"];

                // The HTML editor creates base64 DataURIs which we'll have to convert to image
                // files on disk
                if (srcNode is null || fileNameNode is null)
                {
                    continue;
                }

                var extension = System.IO.Path.GetExtension(fileNameNode.Value);

                // Only accept image files
                if (!allowedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }

                var base64Match = base64Regex.Match(srcNode.Value);
                if (base64Match.Success)
                {
                    var bytes = Convert.FromBase64String(base64Match.Groups["base64"].Value);
                    srcNode.Value = await this.blog.SaveFile(bytes, fileNameNode.Value).ConfigureAwait(false);

                    img.Attributes.Remove(fileNameNode);
                    post.Content = post.Content.Replace(match.Value, img.OuterXml, StringComparison.OrdinalIgnoreCase);
                }
            }
        }

19 View Source File : ImapUTF7.cs
License : Apache License 2.0
Project Creator : azanov

public static string Encode(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;

            value = value.Replace("&", "&-");

            var rex = new Regex("[^ -~]*");
            var encoding = new UnicodeEncoding(true, false);

            IEnumerable<Match> toEncode =
                rex.Matches(value).Cast<Match>().Where(_ => !string.IsNullOrEmpty(_.Value));

            foreach (Match match in toEncode)
            {
                string b64 = "&" + Base64.ToBase64(encoding.GetBytes(match.Value)).TrimEnd('=').Replace("/", ",") +
                             "-";
                value = value.Replace(match.Value, b64);
            }

            return value;
        }

19 View Source File : ImapUTF7.cs
License : Apache License 2.0
Project Creator : azanov

public static string Decode(string name)
        {
            string result = name.Replace("&-", "&");
            var encoding = new UnicodeEncoding(true, false);
            var rex = new Regex(@"&[\w|,|\+]*-");

            MatchCollection matches = rex.Matches(name);

            foreach (Match m in matches)
            {
                string v = m.Value.TrimStart('&').TrimEnd('-').Replace(",", "/");
                v += v.Length%4 == 2 ? "==" : (v.Length%4 == 3 ? "=" : "");
                var data = Base64.FromBase64(v);
                result = result.Replace(m.Value, encoding.GetString(data, 0, data.Length).Replace("\0", ""));
            }

            return result;
        }

19 View Source File : KustoDataProvider.cs
License : MIT License
Project Creator : Azure

public async Task<DataTable> ExecuteClusterQuery(string query, string requestId = null, string operationName = null)
        {
            if(!query.Contains("geneva_metrics_request"))
            {
                //Allow partner KQL queries to proxy through us
                var matches = Regex.Matches(query, @"cluster\((?<cluster>([^\)]+))\).database\((?<database>([^\)]+))\)\.");
                if (matches.Any())
                {
                    foreach (Match element in matches)
                    {
                        string targetCluster = element.Groups["cluster"].Value.Trim(new char[] { '\'', '\"' });
                        string targetDatabase = element.Groups["database"].Value.Trim(new char[] { '\'', '\"' });

                        if (!string.IsNullOrWhiteSpace(targetCluster) && !string.IsNullOrWhiteSpace(targetDatabase))
                        {
                            targetCluster = targetCluster.Replace(".kusto.windows.net", string.Empty, StringComparison.OrdinalIgnoreCase);
                            return await ExecuteClusterQuery(query, targetCluster, targetDatabase, requestId, operationName);
                        }
                    }
                }
            }            

            return await ExecuteQuery(query, DataProviderConstants.FakeStampForreplacedyticsCluster, requestId, operationName);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : Azure

public static string MakeQueryCloudAgnostic(IKustoMap kustoMap, string query)
        {
            if (kustoMap == null)
            {
                throw new ArgumentNullException(nameof(kustoMap));
            }

            if (string.IsNullOrWhiteSpace(query))
            {
                throw new ArgumentNullException(nameof(query));
            }

            var matches = Regex.Matches(query, @"cluster\((?<cluster>([^\)]+))\).database\((?<database>([^\)]+))\)\.");

            if (matches.Any())
            {
                foreach (Match element in matches)
                {
                    var targetCluster = kustoMap.MapCluster(element.Groups["cluster"].Value.Trim(new char[] { '\'', '\"' }));
                    var targetDatabase = kustoMap.MapDatabase(element.Groups["database"].Value.Trim(new char[] { '\'', '\"' }));

                    if (!string.IsNullOrWhiteSpace(targetCluster) && !string.IsNullOrWhiteSpace(targetDatabase))
                    {
                        query = query.Replace($"cluster({element.Groups["cluster"].Value})", $"cluster('{targetCluster}')");
                        query = query.Replace($"database({element.Groups["database"].Value})", $"database('{targetDatabase}')");
                    }
                }
            }

            return query;
        }

19 View Source File : DevOpsClient.cs
License : MIT License
Project Creator : Azure

public async Task<List<DevopsFileChange>> GetFilesInCommit(string commitId)
        {
            if (string.IsNullOrWhiteSpace(commitId))
                throw new ArgumentNullException("commit id cannot be null");
            CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(DataProviderConstants.DefaultTimeoutInSeconds));
            GitRepository repositoryAsync = await gitClient.GetRepositoryAsync(_project, _repoID, (object)null, tokenSource.Token);
            GitCommitChanges changesAsync = await gitClient.GetChangesAsync(commitId, repositoryAsync.Id, null, null, null, tokenSource.Token);
            List<DevopsFileChange> stringList = new List<DevopsFileChange>();
            foreach (GitChange change in changesAsync.Changes)
            {
                var diagEnreplacedy = new DiagEnreplacedy();
                var gitversion = new GitVersionDescriptor
                {
                    Version = commitId,
                    VersionType = GitVersionType.Commit,
                    VersionOptions = GitVersionOptions.None
                };
                if (change.Item.Path.EndsWith(".csx") && (change.ChangeType == VersionControlChangeType.Add || change.ChangeType == VersionControlChangeType.Edit))
                {
                    // hack right now, ideally get from config
                    var detectorId = String.Join(";", Regex.Matches(change.Item.Path, @"\/(.+?)\/")
                                        .Cast<Match>()
                                        .Select(m => m.Groups[1].Value));


                    Task<string> detectorScriptTask = GetFileContentInCommit(repositoryAsync.Id, change.Item.Path, gitversion);
                    Task<string> packageContentTask = GetFileContentInCommit(repositoryAsync.Id, $"/{detectorId}/package.json", gitversion);
                    Task<string> metadataContentTask = GetFileContentInCommit(repositoryAsync.Id, $"/{detectorId}/metadata.json", gitversion);
                    await Task.WhenAll(new Task[] { detectorScriptTask, packageContentTask, metadataContentTask });
                    string detectorScriptContent = await detectorScriptTask;
                    string packageContent = await packageContentTask;
                    string metadataContent = await metadataContentTask;
                    if (packageContent != null)
                    {
                        diagEnreplacedy = JsonConvert.DeserializeObject<DiagEnreplacedy>(packageContent);
                    } else
                    {
                        throw new Exception("Package.json cannot be empty or null");
                    }
                    stringList.Add(new DevopsFileChange
                    {
                        CommitId = commitId,
                        Content = detectorScriptContent,
                        Path = change.Item.Path,
                        PackageConfig = packageContent,
                        Metadata = metadataContent,
                        Id = diagEnreplacedy.DetectorId
                    });
                }
                else if (change.Item.Path.EndsWith(".csx") && (change.ChangeType == VersionControlChangeType.Delete))
                {
                    var detectorId = String.Join(";", Regex.Matches(change.Item.Path, @"\/(.+?)\/")
                                        .Cast<Match>()
                                        .Select(m => m.Groups[1].Value));

                    GitCommit gitCommitDetails = await gitClient.GetCommitAsync(commitId, repositoryAsync.Id, null, null, tokenSource.Token);
                    // Get the package.json from the parent commit since at this commit, the file doesn't exist.
                    var packageContent = await GetFileContentInCommit(repositoryAsync.Id, $"/{detectorId}/package.json", new GitVersionDescriptor
                    {
                        Version = gitCommitDetails.Parents.FirstOrDefault(),
                        VersionType = GitVersionType.Commit,
                        VersionOptions = GitVersionOptions.None
                    });
                    
                    if (packageContent != null)
                    {
                        diagEnreplacedy = JsonConvert.DeserializeObject<DiagEnreplacedy>(packageContent);
                    }
                    else
                    {
                        throw new Exception("Package.json cannot be empty or null");
                    }
                    // Mark this detector as disabled. 
                    stringList.Add(new DevopsFileChange
                    {
                        CommitId = commitId,
                        Content = "",
                        PackageConfig = packageContent,
                        Path = change.Item.Path,
                        Metadata = "",
                        MarkAsDisabled = true,
                        Id = diagEnreplacedy.DetectorId
                    });
                }
            }
            return stringList;
        }

19 View Source File : DirectContractTests.cs
License : MIT License
Project Creator : Azure

private static Dictionary<string, Version> GetPackageReferencies(string csprojName)
        {
            string fullCsprojName = Path.Combine(Directory.GetCurrentDirectory(), csprojName);
            Trace.TraceInformation($"Testing dependencies for csporj file {fullCsprojName}");
            string projContent = File.ReadAllText(fullCsprojName);

            Regex projRefMatcher = new Regex("<PackageReference\\s+Include=\"(?<Include>[^\"]*)\"\\s+Version=\"(?<Version>[^\"]*)\"\\s+(Privatereplacedets=\"(?<Privatereplacedets>[^\"]*)\")?");
            MatchCollection matches = projRefMatcher.Matches(projContent);

            int prjRefCount = new Regex("<PackageReference").Matches(projContent).Count;
            replacedert.AreEqual(prjRefCount, matches.Count, "CSPROJ PackageReference regex is broken");

            Dictionary<string, Version> projReferences = new Dictionary<string, Version>();
            foreach (Match m in matches)
            {
                if (m.Groups["Privatereplacedets"].Captures.Count != 0)
                {
                    replacedert.AreEqual("All", m.Groups["Privatereplacedets"].Value, $"{m.Groups["Include"].Value}");
                }
                else
                {
                    projReferences[m.Groups["Include"].Value] = Version.Parse(m.Groups["Version"].Value);
                }
            }

            return projReferences;
        }

19 View Source File : DirectContractTests.cs
License : MIT License
Project Creator : Azure

private static Dictionary<string, Version> GetNuspecDependencies(string nuspecFile)
        {
            Trace.TraceInformation($"Testing dependencies for nuspec file {nuspecFile}");
            string nuspecContent = File.ReadAllText(nuspecFile);

            Regex regexDepMatcher = new Regex("<dependency\\s+id=\"(?<id>[^\"]*)\"\\s+version=\"(?<version>[^\"]*)\"");
            MatchCollection matches = regexDepMatcher.Matches(nuspecContent);

            int dependencyCount = new Regex("<dependency").Matches(nuspecContent).Count;
            replacedert.AreEqual(dependencyCount, matches.Count, "Nuspec dependency regex is broken");

            Dictionary<string, Version> dependencies = new Dictionary<string, Version>();
            foreach (Match m in matches)
            {
                dependencies[m.Groups["id"].Value] = Version.Parse(m.Groups["version"].Value);
            }

            return dependencies;
        }

19 View Source File : ConfigData.cs
License : MIT License
Project Creator : Azure

private void ProcessMandatoryPlaceholders(ref string value)
        {
            // Pattern for mandatory replacements: ${VAR_NAME}
            const string PATTERN = @"\${([a-zA-Z_][a-zA-Z0-9_]*)}";

            // Search
            var keys = (from Match m in Regex.Matches(value, PATTERN)
                        select m.Groups[1].Value).Distinct().ToArray();

            // Replace
            foreach (DictionaryEntry x in Environment.GetEnvironmentVariables())
            {
                if (keys.Contains(x.Key))
                {
                    value = value.Replace("${" + x.Key + "}", x.Value.ToString());
                }
            }

            // Non replaced placeholders cause an exception
            keys = (from Match m in Regex.Matches(value, PATTERN)
                    select m.Groups[1].Value).ToArray();
            if (keys.Length > 0)
            {
                var varsNotFound = keys.Aggregate(", ", (current, k) => current + k);
                this.log.Error("Environment variables not found", () => new { varsNotFound });
                throw new InvalidConfigurationException("Environment variables not found: " + varsNotFound);
            }
        }

19 View Source File : ConfigData.cs
License : MIT License
Project Creator : Azure

private void ProcessOptionalPlaceholders(ref string value, out bool notFound)
        {
            notFound = false;

            // Pattern for optional replacements: ${?VAR_NAME}
            const string PATTERN = @"\${\?([a-zA-Z_][a-zA-Z0-9_]*)}";

            // Search
            var keys = (from Match m in Regex.Matches(value, PATTERN)
                        select m.Groups[1].Value).Distinct().ToArray();

            // Replace
            foreach (DictionaryEntry x in Environment.GetEnvironmentVariables())
            {
                if (keys.Contains(x.Key))
                {
                    value = value.Replace("${?" + x.Key + "}", x.Value.ToString());
                }
            }

            // Non replaced placeholders are removed
            keys = (from Match m in Regex.Matches(value, PATTERN)
                    select m.Groups[1].Value).ToArray();
            if (keys.Length > 0)
            {
                // Remove placeholders
                value = keys.Aggregate(value, (current, k) => current.Replace("${?" + k + "}", string.Empty));

                var varsNotFound = keys.Aggregate(", ", (current, k) => current + k);
                this.log.Warn("Environment variables not found", () => new { varsNotFound });

                notFound = true;
            }
        }

19 View Source File : ConfigData.cs
License : MIT License
Project Creator : Azure

private static string ReplaceEnvironmentVariables(string value)
        {
            if (string.IsNullOrEmpty(value)) return value;

            // Extract the name of all the subsreplacedutions required
            // using the following pattern, e.g. ${VAR_NAME}
            const string pattern = @"\${(?'key'[a-zA-Z_][a-zA-Z0-9_]*)}";
            var keys = (from Match m
                        in Regex.Matches(value, pattern)
                        select m.Groups[1].Value).ToArray();

            foreach (DictionaryEntry x in Environment.GetEnvironmentVariables())
            {
                if (keys.Contains(x.Key))
                {
                    value = value.Replace("${" + x.Key + "}", x.Value.ToString());
                }
            }

            return value;
        }

See More Examples