Himberjack
Himberjack

Reputation: 5792

How to regex c# string

I have the following string, and I am trying to extract only the content within the FUNC( ):

FUNC(strToExtract)

I'm having trouble in extracting it using Regex.Replace()

Kind help would be appreciated

thanks

Upvotes: 0

Views: 161

Answers (3)

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

Try this:

string input = "Func(params)";
string pattern = @"\w+\((.+?)\)";
Match m = Regex.Match(input, pattern);
string result = m.Groups[1].Value;
Console.WriteLine(result);

The parentheses must be escaped, otherwise they'll be interpreted as a regex group. The .+? will match at least one character and is not greedy, so it won't match more than necessary if multiple matches exist in the same input. The use of \w+ makes the pattern flexible enough to handle different function names, not just "Func."

Upvotes: 0

Bazzz
Bazzz

Reputation: 26922

if you know the string will always start with "FUNC(" and ends with ")" then not using a regex is a lot cheaper:

string myString = "FUNC(strToExtract)";
string startsWith = "FUNC(";
string endsWith = ")";
if (myString.StartsWith(startsWith) && myString.EndsWith(endsWith))
{
  string extracted = myString.Substring(startsWith.Length, myString.Length - endsWith.Length - startsWith.Length);
}

Upvotes: 2

Wavyx
Wavyx

Reputation: 1745

Hi you can try something like this:

Regex regexp = new Regex(@"FUNC((.*))", RegexOptions.IgnoreCase);
MatchCollection matches = regexp.Matches(inputString);
Match m = matches[0];
Group g = m.Groups[0];

Edit: removed the escaped () in @"FUNC((.*))"

Upvotes: 1

Related Questions