Faizal
Faizal

Reputation: 1833

C# Regular Expressions, string between single quotes

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";

i want to get the text between ' quotes using Regular Expressions.

Can anyone?

Upvotes: 14

Views: 25101

Answers (4)

firefox1986
firefox1986

Reputation: 1612

This will extract the text between the first and last single quote on a line:

string input = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
Regex regName = new Regex("'(.*)'");
Match match = regName.Match(input);
if (match.Success)
{
    string result = match.Groups[1].Value;
    //do something with the result
}

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

You could use positive lookahead and lookbehind also,

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";

Match match = Regex.Match(val, @"(?<=')[^']*(?=')");
if (match.Success)
{
    string yourValue = match.Groups[0].Value;
    Console.WriteLine(yourValue);
}

Upvotes: 2

Jaapjan
Jaapjan

Reputation: 3385

You are looking to match GUID's in a string using a regular expression.

This is what you want, I suspect!

public static Regex regex = new Regex(
  "(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-"+
  "([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})",RegexOptions.CultureInvariant|RegexOptions.Compiled);

Match m = regex.Match(lineData);
if (m.Succes)
{
...
}

Upvotes: 3

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

Something like this should do it:

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";

Match match = Regex.Match(val, @"'([^']*)");
if (match.Success)
{
    string yourValue = match.Groups[1].Value;
    Console.WriteLine(yourValue);
}

Explanation of the expression '([^']*):

 '    -> find a single quotation mark
 (    -> start a matching group
 [^'] -> match any character that is not a single quotation mark
 *    -> ...zero or more times
 )    -> end the matching group

Upvotes: 42

Related Questions