Attention: We are retiring the ASP.NET Community Blogs. Learn more >

\G - match at the end of the previous match.

Over the next few days I'd like to spend a bit of time looking at using \G in the .NET "flavour" of regular expressions.  I'd love to hear from anyone that has *had* to use \G in a real-world application (.NET only).

In the meantime, consider the following two snippets...

WITH \G

using System ;
using System.Text.RegularExpressions ;

namespace Regex Snippets.Tests
{
	public class Foo
	{
		public static void Main()
		{
			string source = @"111111111" ;
			string replacement = @"%" ;
			string pattern = @"\Gx?" ;

			string newString = 
			        Regex.Replace( 
			        source,
					pattern,
					replacement
				) ;
 			
			Console.WriteLine( "Input string: {0}", source ) ; 
			Console.WriteLine( "Output string: {0}", newString ) ; 
			Console.ReadLine() ; 
		}
	}
}
Result: %111111111




WITHOUT \G

using System ;
using System.Text.RegularExpressions ;

namespace Regex Snippets.Tests
{
	public class Foo
	{
		public static void Main()
		{
			string source = @"111111111" ;
			string replacement = @"%" ;
			string pattern = @"x?" ;

			string newString = 
			        Regex.Replace( 
			        source,
					pattern,
					replacement
				) ;
 			
			Console.WriteLine( "Input string: {0}", source ) ; 
			Console.WriteLine( "Output string: {0}", newString ) ; 
			Console.ReadLine() ; 
		}
	}
}
Result: %1%1%1%1%1%1%1%1%1%
 
Note: added results.

No Comments