有一个文本文件,如:
我的名字叫山姆
我的0.22 1.65
名称2.21 2.99
是3.31 4.12
山姆4.97 5.95
我要拒绝只有一句话的第一句话。
我想考虑包含单词和数字的语句,以便将其放入数组中。
我如何在Regex中做到这一点?
我的代码适用于英语,但不适用于中文这样的字符。
while ((line2 = streamReader2.ReadLine()) != null)
{
// If line contains numbers and words, then split if by space and store in an array.
if (Regex.IsMatch(line2, @"[^0-9\p{L}_ ]+", RegexOptions.IgnoreCase))
{
wordArray = line2.Split(null); //split each string by blankspace
}
}
答案 0 :(得分:1)
您可以在此处省略正则表达式,并使用if (line2.Any(Char.IsDigit) && line2.Any(Char.IsLetter))
。仅当该行同时包含Unicode字母和任何Unicode数字时,才返回true。
然后,使用以下修复程序:
var wordArray = new List<String[]>(); // Declare wordArray
while ((line2 = streamReader2.ReadLine()) != null)
{
if (line2.Any(Char.IsDigit) && line2.Any(Char.IsLetter)) // If line2 contains letter and digit
wordArray.Add(line2.Split()); // Add the line split with whitespace to wordArray
}
请参见C# demo