1

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?

1
  • Are you by any chance trying to parse C# code with a regex as your pattern looks pretty close to C#? Commented Nov 24, 2010 at 8:42

6 Answers 6

1

This should help you build any regular expressions you need:

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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]+)

2 Comments

From this pattern i want only the method name.(not entirely the pattern) . Thank you
@prem: I think this is closer to what you're searching - ^public\s+\w\s+$'\w
0

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.

Comments

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

Gets word after the matched pattern.

Comments

0

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?

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.