Saobi
Saobi

Reputation: 17041

How to construct this in regular expression

I want to match the pattern: Starts with 0 or more spaces, followed by "ABC", then followed by anything.

So things like " ABC " " ABC111111" "ABC" would be matched.
But things like " AABC" "SABC" would not be matched.

I tried:

String Pattern = "^\\s*ABC(.*)";

But it does not work.

Any ideas? This is in C# by the way.

Upvotes: 0

Views: 223

Answers (4)

Rashmi Pandit
Rashmi Pandit

Reputation: 23858

I tested this. It works. You can omit RegexOptions.IgnoreCase if you want only upper case ABC to be matched.

/// <summary>
/// Gets the part of the string after ABC
/// </summary>
/// <param name="input">Input string</param>
/// <param name="output">Contains the string after ABC</param>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetStringAfterABC(string input, out string output)
{
    output = null;

    string pattern = "^\\s*ABC(?<rest>.*)";

    if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
    {
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        output = r.Match(input).Result("${rest}");
        return true;
    }
    else
        return false;
}

Calling code:

static void Main(string[] args)
{
    string input = Console.ReadLine();

    while (input != "Q")
    {
        string output;
        if (MyRegEx.TryGetStringAfterABC(input, out output))
            Console.WriteLine("Output: " + output);
        else
            Console.WriteLine("No match");
        input = Console.ReadLine();
    }
}

Upvotes: 1

Mark
Mark

Reputation: 6128

The \\ usually puts in a literal backslash so that's probably where your solution is failing. Unless you are doing a replace you don't need the parentheses around the .*

Also \s matches characters besides the space character [ \t\n\f\r\x0B] or space, tab, newline, formfeed, return, and Vertical Tab.

I would suggest:

String Pattern = @"^[ ]*ABC.*$";  

Upvotes: 1

SolutionYogi
SolutionYogi

Reputation: 32243

Try

string pattern = @"\s*ABC(.*)"; // Using @ makes it easier to read regex. 

I verified that this works on regexpl.com

Upvotes: 2

Alan McBee
Alan McBee

Reputation: 4320

Be sure you have set the regex engine to use SingleLine and not MultiLine.

Upvotes: 0

Related Questions