C#reformating串入读值使用正则表达式或其他方法
问题描述:
我有一个字符串,它基本上看起来像这样在我的编译器:C#reformating串入读值使用正则表达式或其他方法
\n $\n22\n95\n\n
我想它格式化为一个字符串,它看起来像如下:
22.95
这是可以在C#中吗?特别是因为在字符串中只有\ n,我不知道如何过滤它?
答
你能做到这一点的方式如下:
1)使用Split方法
2)使用where和int.TryParse筛选方法
3)再结合生成的拆分通过'\n'
字符串收集到一个字符串使用String.Join与"."
作为分隔符
请试试这个算法, ñ发布你的尝试,我会给你全部的代码。用linq只有1行代码。请给我留言,如果你在路上
答
这里的困难是一个简单的实施Mong Zhu's answer:
private static string StringDouble(string input)
{
var intSplitResult =
input.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(str =>
{
int value;
bool success = int.TryParse(str, out value);
return new { value, success };
})
.Where(pair => pair.success)
.Select(pair => pair.value);
if (intSplitResult.Count() != 2)
{
throw new ArgumentException(
$"Invalid Input: [{input}]. Do not contains the right number of number!"
, nameof(input));
}
return string.Join(".", intSplitResult);
}
答
in two steps using first positive look behind and positive look ahead
then replacing non digit and non dot.
var text = "\n $\n22\n95\n\"
var pattern = @"((?<=\d+))(\n)((?=\d+))";
var st = Regex.Replace(text, pattern, @"$1.$3")
st = Regex.Replace(st, @"[^\d.]", "");