简体   繁体   中英

How to take a specific word from a dynamic string

I'm trying to take or select a specific word from a dynamic string value using c#.

Example :

Here is some Text before Vol.20 Here is some text after

I want to take => Vol.20

Here is some Text before Vol.1 Here is some text after

I want to take => Vol.1

Here is some Text before Vol.777 Here is some text after

I want to take => Vol.777

As you see in the example always there is text before and after Vol.20 & Vol.1 & Vol.777 also the only constant in this string is Vol.[number]

I only want to take the Vol.Number as string and save it .

You can use RegEx for that, for example:

string str = "Here is some Text before Vol.1 Here is some text after";

Regex rg = new Regex(@"Vol.\d*"); //If number reqired use Vol.\d+
Match match = rg.Match(str);
string result = match.Value;

match.Value will return empty string if no match will be found, or you can use match.Success to check if there is a match.

Of course you can do it without regex, for example this way:

string result = string.Concat(str.Split(' ').Where(s => s.Contains("Vol.")));

but I will prefer regex version.

All this versions for if there is only one Vol.[Number] inside string, for multiple instances, you can do this:

string str = "Vol.551 Here is some Text before Vol.1 Vol.12 Here is some text after Vol.143";

Regex rg = new Regex(@"Vol.\d*"); //If number reqired use Vol.\d+

Match match = rg.Match(str);

MatchCollection matches = rg.Matches(str);

foreach (var item in matches)
{
    //Do something with item.Value
}

And non-regex version:

string[] matches = str.Split(' ').Where(s => s.Contains("Vol.")).ToArray();

Again, I will prefer regex version over above one. But if your strings is not too big and you have no issues with performance, you can use either of them.

References: Regex Class

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