简体   繁体   中英

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 string contains any environment variable? Of course I can compare string before and after expanding, but is there more elegant way to do that?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM