c# - 尝试使用 LINQ 仅过滤字符串数组中的数字
问题描述
我正在尝试仅过滤字符串数组中的数字。如果我有这个数组:12324 asddd 123 123,这可以工作,但如果我在一个字符串中有字符和数字,例如 asd1234,它不会接受它。你能帮我怎么做吗?
int[] result = input
.Where(x => x.All(char.IsDigit))// tried with .Any(), .TakeWhile() and .SkipWhile()
.Select(int.Parse)
.Where(x => x % 2 == 0)
.ToArray();
解决方案
如果我在一个字符串中包含字符和数字,例如 asd1234,它不会接受它
显然你也想解析这一行。您想将“asd1234”翻译成“1234”,然后解析它。
但是,如果您的输入字符串序列包含一个带有两个数字的字符串:“123asd456”。您想将其解释为“123”,还是“123456”,或者您将其视为两个数字“123”和“456”。
假设您没有这个问题:每个字符串最多包含一个数字,或者如果您有一个包含多个数字的字符串,您只需要第一个数字。
实际上,您只想保留那些“零个或多个非数字后跟一个或多个数字后跟零个或多个字符”的字符串。
输入正则表达式!
const string regexTxt = "\D*\d+.*";
Regex regex = new Regex(regexTxt);
- \D:任何非数字
- *:零个或多个
- \d:任何数字
- +:一个或多个
- . 任何字符
- (...) 捕获括号之间的部分
所以这个正则表达式匹配任何以零个或多个非数字开头,后跟至少一个数字,后跟零个或多个字符的字符串。捕获“至少一位数字”部分。
如果您尝试Match()
使用此正则表达式输入字符串,则会得到一个Match
对象。属性Success
告诉你输入的字符串是否符合正则表达式。
该Match
对象有一个Groups
包含所有匹配项的属性。Groups[0] 是完整的字符串,Groups 1包含一个Group
在 property 中具有第一个捕获的字符串的a Value
。
一个简单的程序,展示了如何使用正则表达式:
const string regexTxt = @"\D*(\d+).*";
Regex regex = new Regex(regexTxt);
var lines = new string[]
{
String.Empty,
"A",
"A lot of text, no numbers",
"1",
"123456",
"Some text and then a number 123",
"Several characters, then a number: 123 followed by another number 456!",
"___123---456...",
};
foreach (var line in lines)
{
Match match = regex.Match(line);
if (match.Success)
{
string capturedDigits = match.Groups[1].Value;
int capturedNumber = Int32.Parse(capturedDigits);
Console.WriteLine("{0} => {1}", line, capturedNumber);
}
}
或者在 LINQ 语句中:
const string regexTxt = @"\D*(\d+).*";
Regex regex = new Regex(regexTxt);
IEnumerable<string> sourceLines = ...
var numbers= sourceLines
.Select(line => regex.Match(line)) // Match the Regex
.Where(match => match.IsMatch) // Keep only the Matches that match
.Select(match => Int32.Parse(match.Groups[1].Value);
// Finally Parse the captured text to int
推荐阅读
- html - 如何将单页应用程序与 express-handlebars 一起使用?
- c++ - Eclipse 为 C++ 项目运行“在 '/git' 上调用 'Java Builder'”
- salesforce - 如何在 Visualforce 中使用 Handlebars 为一个父表显示 2 个子表
- airflow - 气流 2.0.1 中的 MysqlOperator 因“ssl 连接错误”而失败
- javascript - 如何使用 nodeJS 从 AmazonS3 获取音频文件
- user-interface - 控制应用程序安装
- php - php laravel 严格的对象转换
- python - 按日期python对目录中的多个csv文件进行排序
- javascript - 我可以在指针图像上分层图像吗
- vba - 从 DLL 创建具有现有名称的类方法