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
CodePudding user response:
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);