For example, I have this string that could change anytime I only want the alphabetic text from it:
Ferrari 5 10 15000 -5 0.2
So from that I want "Ferrari".
Sometimes there won't be a space between "Ferrari" and the numbers.
string str = "Ferrari 5 10 15000 -5 0.2";
string text = Regex.Match(str, @"[a-zA-Z\s]+").Value.Trim();
By also matching whitespace and then trimming the result, It will match "Some Car"
in "Some Car 5 10 ..."
.
Using regex you can just match the initial letters like so
string text = "Ferrari 5 10 15000 -5 0.2";
string pat = @"([a-z]+)";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
你可以用
String s = Regex.Match(str, @"[a-zA-Z]+").Value;
One option would be to convert to a char array and pull out the letters and then convert back to a string:
string text = "Ferrari 5 10 15000 -5 0.2";
string alphas = string.Join( "", text.ToCharArray().Where( char.IsLetter ) );
This is one of the times when Regular Expressions come in handy :
Regex wordMatcher = new Regex("[a-zA-Z]+");
foreach(Match m in wordMatcher.Matches("Ferrari 55 100000 24 hello"))
MessageBox.Show(m.Value);
Essentially all The RegEx does is attempt to match groups of letters between az ignoring case.
If it will always end with [digits, -, ., and spaces], you can use .TrimEnd
:
record.TrimEnd("0123456789 .-".ToCharArray());
... or if there's no spaces in the text you care about, you can read until the first space ...
var whatINeed = new string(record.TakeWhile(c => c != ' ').ToArray());
... or just take the first item when split on spaces ...
var whatINeed = record.Split().First();
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.