0

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

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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((.*))"

5 Comments

Didnt work. I succeeded in doing egex.Replace("FUNC(foaksdokfakosdfko)", @"FUNC((.*))", "$1")
Sorry, I didn't test it. And I thought you should escape the () from the FUNC method. Happy you find the solution ;)
I don't think this is going to work for the following 2 reasons: 1) the brackets should be escaped appropriately, 2) the closing bracket will be matched by .* because the matching is greedy and so the bracket at the end is never matched. EDIT: perhaps the brackets don't need to be escaped when using @ .. just guessing
They do still need to be escaped.
Won't a regex on "FUNC ..." always return the value of FUNC? I think he wants the value within the braces, if you want to compare the FUNC, you'd do the <= pre-look thing for FUNC( but not actually return the FUNC.
0

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."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.