0

I have this sample string

`{1:}{2:}{3:}{4:\r\n-}{5:}`

and I want to extract out only {4:\r\n-}

This is my code but it is not working.

var str = "{1:}{2:}{3:}{4:\r\n-}{5:}";
var regex = new Regex(@"{4:*.*-}");
var match = regex.Match(str);
Steve
  • 2,963
  • 15
  • 61
  • 133
  • Does this answer your question? [What special characters must be escaped in regular expressions?](https://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions) – Charlieface Feb 06 '22 at 11:22

2 Answers2

1

You need to escape the special regex characters (in this case the opening and closing braces and the backslashes) in the search string. This would capture just that part:

var regex = new Regex("\{4:\\r\\n-\}");

... or if you wanted anything up to and including the slash before the closing brace (which is what it looks like you might be trying to do)...

var regex = new Regex("\{4:[^-]*-\}");
Russ
  • 26
  • 2
0

You just need to escape your \r and \n characters in your regular expression. You can use the Regex.Escape() method to escape characters in your regex string which returns a string of characters that are converted to their escaped form.

Working example: https://dotnetfiddle.net/6GLZrl

using System;
using System.Text.RegularExpressions;
                
public class Program
{
    public static void Main()
    {
        string str = @"{1:}{2:}{3:}{4:\r\n-}{5:}";
        string regex = @"{4:\r\n-}";  //Original regex
        Match m = Regex.Match(str, Regex.Escape(regex));
        if (m.Success)
        {
            Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);        
        }
        else
        {
            Console.WriteLine("No match found");        
        }
    }
} 
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54