user1619672
user1619672

Reputation: 269

C# regular expression

I want to fetch the text from line using regex

eg :

 string xyz = "text/plain; charset=US-ASCII; name=\"anythingfile.txt\"";

and i want to fetch the anythingfile.txt from that line

that mean i want to create regex that match the pattern name="" and fetch string between double quotes I tried with this

regex re= new regex(@"name="\"[\\w ]*\""")

but not getting proper result ....plz help me.

Upvotes: 0

Views: 1313

Answers (3)

huysentruitw
huysentruitw

Reputation: 28091

Best approach is to use a named group:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string xyz = "text/plain; charset=US-ASCII; name=\"anythingfile.txt\"";
        Match m = Regex.Match(xyz, "name=\"(?<name>[^\"]+)\"");
        Console.WriteLine(m.Groups["name"].Value);
        Console.ReadKey();
    }
}

Upvotes: 0

L.B
L.B

Reputation: 116108

Do you really need regex? Simple string operations may be enough:

var NameValue = xyz.Split(';')
                   .Select(x => x.Split('='))
                   .ToDictionary(y => y.First().Trim(), y => y.LastOrDefault());

Upvotes: 1

John Woo
John Woo

Reputation: 263703

try this Regex Pattern,

(?<=name="").*(?="")

Upvotes: 1

Related Questions