kayewan kayewan - 27 days ago 12
C# Question

C# getting variables from a CAST statement using Regex

I have the following input string:

String text = "Cast(@myvar AS datetime)";


Is there some way by which I could extract the variable and datatype used using regex?

Expected output:

name ='@myvar'
type ='datetime'

Answer

You could use the following Expression and use the capturing groups to get the pairs:

(?<=cast\()(.*)(?:\s+as\s+)(.*)(?=\))

See at Regex101

var text = "Cast(@myvar1 AS datetime2)" + Environment.NewLine + "Cast(@myvar2 AS datetime2)";

var matches = new Regex(@"(?<=cast\()(.*?)(?:\s+as\s+)(.*?)(?=\))", RegexOptions.IgnoreCase).Matches(text);

foreach(Match match in matches)
{
    // first capturing group will be full match, so we need to start with index 1 for actual group 1
    var name = match.Groups[1];
    var type = match.Groups[2];

    Console.WriteLine("Name: {0}, Type: {1}", name, type);
}

// Name: @myvar1, Type: datetime2
// Name: @myvar2, Type: datetime2
Comments