Cant find the right Regex pattern

Viewed 32

I'm trying to get a variable that cold be between the '[var]' or '[var["something"]]'.

Example no.1: If the string is: str = "[AgentStateTime]";

The output should be: AgentStateTime

Example no.2: If the string is: str = "[AgentStateTime["Break"]";

The output should be: AgentStateTime

What is the pattern that works for both?

2 Answers

Look for words preceded by a [ that are followed by either a [ or a ]:

var inputStrings = new string[] { "[AgentStateTime]", "[AgentStateTime[\"Break\"]"};

foreach (var input in inputStrings){
    var match = Regex.Match(input, @"(?<=\[)\w+(?=[\[\]])");
    if(match.Success){
        Console.WriteLine("Input was: {0}", input);
        Console.WriteLine("Match was: {0}", match.Value);
    }
}

Which outputs:

Input was: [AgentStateTime]
Match was: AgentStateTime
Input was: [AgentStateTime["Break"]
Match was: AgentStateTime

It depends. But basically, you can use alternate (|) operator

Are you sure the only thing that you will have inside the "[]" is string? If yes, this should work:

\[(\w+)(\]|\[)

The first group of this regex will have the result that you are expecting. If you always are looking to a var declaration, you can filter it to this:

\w+\s\=\s\"\[(\w+)(\]|\[)

You can adapt it to be more generic according to the result that you want.

Related