简体   繁体   中英

Match the pattern in the string using c#

Let's say my texts are:

New York, NY is where I live.
Boston, MA is where I live.
Kentwood in the Pines, CA is where I live.

How do I extract just "New York", "Boston", "Kentwood in the Pines" .

I can extract State name by pattern @"\\b,\\s(?"<"state">"\\w\\w)\\s\\w+\\s\\w+\\s\\w\\s\\w+"

I am using regular expression but I'm not able to figure out how to extract city names as city names can be more than two words or three.

Just substring from the beginning of the string to the first comma:

var city = input.Substring(0, input.IndexOf(','));

This will work if your format is always [City], [State] is where I live. and [City] never contains a comma.

this is want you need ..

static void Main(string[] args)
    {
        string exp = "New York, NY is where I live. Boston, MA is where I live. Kentwood in the Pines, CA is where I live.";
        string reg = @"[\w\s]*(?=,)";
        var matches = Regex.Matches(exp, reg);
        foreach (Match m in matches)
        {
            Console.WriteLine(m.ToString());
        }

        Console.ReadLine();
    }

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