开发者

How to regex c# string

I have t开发者_C百科he 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


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);
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜