简体   繁体   中英

How do I retrieve the first alpha character string from withing a longer string using c#

Below are two example strings there I am trying to retrieve a label name from, the first one is retrieved with the .split function, but the second throws an error as the punctuation is not in place, is there a way to select the first set of alpha character until a non alpha character appears? While also removing any non alpha character from the start?

secondSection = secondSection.Split('/', ',')[1];

string example 1
191100201000430<*/SIZENAME,String,5,TOUPPER/*>
string example 2
191100400050100Price

is there a way to select the first set of alpha character until a non alpha character appears? While also removing any non alpha character from the start?

One way, LINQ:

string allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

var alllowedChars = str.SkipWhile(c => !allowed.Contains(c)).TakeWhile(allowed.Contains);
string label = new string(alllowedChars.ToArray());

I suggest using regular expressions and match :

using System.Text.RegularExpressions;

...

// We want 1st non-empty sequence of alpha (a..z A..Z) characters
var result = Regex.Match(str, "[A-Za-z]+").Value;

With a help of regular expressions you can easily get all alpha names (if you want, saym to ignore SIZENAME , String and get TOUPPER ), eg

string[] results = Regex
  .Matches(str, "[A-Za-z]+")
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();

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