Łukasz Kosiak
Łukasz Kosiak

Reputation: 523

Check if string contains environment variable

In .Net we have method Environment.ExpandEnvironmentVariables that allows us to replace all environment variables that provided string contains into its values.

But what if I only want to check if a string contains an environment variable?

Of course, I can compare the string before and after expanding, but is there a more elegant way to do this?

Upvotes: 1

Views: 1818

Answers (1)

Jake
Jake

Reputation: 574

You could create an extension that does a Regex search against the string

public static bool HasEnvironmentVariable(this string path)
{
    Regex regex = new Regex(@"%[A-Za-z0-9\(\)]*%");
    Match match = regex.Match(path);

    return match.Success;
}

Upvotes: 2

Related Questions