开发者

Regular expression in C# .net

I have a pattern in a file as follows:

开发者_开发知识库public "any word" "any word"(

example:

public object QuestionTextExists(QuestionBankProfileHandler QBPH)

Now, I want only the "QuestionTextExists" and any number of space can occur at left and right side of the "object"(Not exactly object, it can be any word). Can anyone Please help me how to do this using regular expression.

Thank You for answers.But how can i extract only the method name from that pattern?


This should help you build any regular expressions you need:

http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/


The expression ^\s*public\s+\w+\s+(\w+)\(.*?\) will do the trick. You can modify it to give more meaningful names. I just used a numbered group. Sample usage :

using System;
using System.Text.RegularExpressions;

class Program
{
    private static Regex regexObj = 
        new Regex(@"^\s*public\s+\w+\s+(\w+)\(.*?\)", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    static void Main(string[] args)
    {
        var testSubject = 
            "public object QuestionTextExists(QuestionBankProfileHandler QBPH)";

        var result = regexObj.Match(testSubject).Groups[1].Value;

        Console.WriteLine(result);
        Console.ReadKey();
    }
}


Assuming the 2nd and 3rd identifiers are only letters, this will put the method names in the first capture group:

^public\s+[A-Za-z]+\s+([A-Za-z]+)


You can use following regex:

^public\s+?(?<id1>[a-zA-Z0-9]+?)\s+?(?<id2>[a-zA-Z0-9]+?)\s+?(

Then matching group named id2 will give you the desired string.

For faster regex execution, create the object of type Regex as a static member of your class and then set its Compiled option on.


^public\s+\w\s+$'\w

Gets word after the matched pattern.


If you pattern is always public[space]word[space]target[bracket]stuffyoudon'tcareabout[bracket] it is simple to achieve without regex. Like so:

string phrase = "public object QuestionTextExists(QuestionBankProfileHandler QBPH)";

string word = phrase.split('(')[0].split(' ')[2];

Is there a reason you want to use regex?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜