In C#, I need to capture variablename in the phrase *|variablename|*.
I’ve got this RegEx: Regex regex = new Regex(@"\*\|(.*)\|\*");
Online regex testers return “variablename”, but in C# code, it returns *|variablename|*, or the string including the star and bar characters. Anyone know why I’m experiencing this return value?
Thanks much!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegExTester
{
class Program
{
static void Main(string[] args)
{
String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Value);
Console.Read();
}
}
}
//Outputs *|variablename|*, instead of variablename
match.Valuecontains the entire match. This includes the delimiters since you specified them in your regex. When I test your regex and input with RegexPal, it highlights*|variablename|*.You want to get only the capture group (the stuff in the brackets), so use
match.Groups[1]: