简体   繁体   中英

Get specific characters within characters' boundaries in a string c#

A newbie in this regard here.

While a code line like the following could return entire set of digits (0 to 9) from a string:

return new string(Entry2BConsidered.Where(char.IsLetter).ToArray());

Is there a similar way to return only characters within boundaries / limits, something like (0 to 5) or (A to E) or (a to e)?

For example in an input like "AbcdE" how to return b to d.

Something like:

public class Program
{
    public static void Main()
    {
        char StartChar = 'b'; char EndChar = 'd';
        String MainString = "AbdcdEAabxdcLdE";
        Console.WriteLine("bdcdabdcd"); //Only characters from b to d required
    }
}

Thanks

Probably the easiest way is a regex. But then i depends what you realy want in detail. Do you want everything between the first b and the last d than thats easy

var input = "AbdcdEAabxdcLdE";
var match = System.Text.RegularExpressions.Regex.Match(input, "b.*d");

if (match.Success)
    Console.WriteLine($"Success: {match.Value}");

for case insensitive search you have two options search for b or B as start character and d or D as end character

var match = System.Text.RegularExpressions.Regex.Match(input, "[bB].*[dD]");

or better make the seach case insensitive by passing an option:

var match = System.Text.RegularExpressions.Regex.Match(input, "b.*d", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

If you want part of the string but only the part the contains letters b to d you could do this:

var match = System.Text.RegularExpressions.Regex.Match(input, "[b-d]+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

Edit: add version to filter all except the given characters

If you want all characters that are between b and d and filter oute everything else you would write:

var input = "AbdcdEAabxdcLdE";
var matches = System.Text.RegularExpressions.Regex.Matches(input, "[b-d]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

var result = string.Join("", matches.Select(m => m.Value));
Console.WriteLine(result);

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