简体   繁体   中英

Get string between a known string and any non-alphanumeric character

I have this code which allows me to get the string between "Global." and " ".

private string getGlobalVariableName(string text)
    {
        int pFrom = text.IndexOf("Global.") + "Global.".Length;
        int pTo = text.LastIndexOf(" ");

        string name = text.Substring(pFrom, pTo - pFrom);

        return name;
    }

I want to modify it so that it gets the string between "Global." and any non-alphanumeric character. How could I do this?

Example:

this is true for what I have now

getGlobalVariableName(" foo Global.bar1 foobar") == "bar1"

this is what I want to be able to do

getGlobalVariableName(" foo Global.bar1>foobar") == "bar1"

You can use Regex...

string input = "Global.bar1>foobar";
var output = Regex.Match(input, @"Global.([\w]+)").Groups[1].Value;

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