Hairgami_Master
Hairgami_Master

Reputation: 5539

How can C# Regex capture everything between *| and |*?

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

Upvotes: 2

Views: 3718

Answers (1)

BoltClock
BoltClock

Reputation: 723498

match.Value contains 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]:

String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Groups[1]);

Upvotes: 12

Related Questions