下面是两个示例字符串,我试图从.split函数中检索一个标签名称,但第二个引发错误,因为标点符号不在位置,有没有办法选择第一组alpha字符,直到出现非alpha字符?同时还从一开始就删除任何非alpha字符?
secondSection = secondSection.Split('/', ',')[1];
string example 1
191100201000430<*/SIZENAME,String,5,TOUPPER/*>
string example 2
191100400050100Price
是否有一种方法可以选择第一组alpha字符,直到非 出现alpha字符?同时还删除任何非alpha字符 从一开始?
一种方式,linq:
string allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alllowedChars = str.SkipWhile(c => !allowed.Contains(c)).TakeWhile(allowed.Contains);
string label = new string(alllowedChars.ToArray());
我建议使用正则表达式和 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;
在正则表达式的帮助下,您可以轻松获取所有alpha名称(如果需要,请忽略 SIZENAME
, String
和get TOUPPER
),例如
string[] results = Regex
.Matches(str, "[A-Za-z]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();