c# - 在大字符串中查找浮点

标签 c# regex string floating-point double

我有一个大字符串,字符串中有一系列浮点。典型的字符串将具有 Item X $4.50 Description of item\r\n\r\n Item Z $4.75... 文本确实没有押韵或原因。我已经有了最低的值,我需要找到字符串中的所有值。因此,如果它是 10.00,它将找到 10.05 或更小的每个值。我假设需要某种正则表达式来查找值,然后我可以将它们放入数组中然后对它们进行排序。

因此,找到这些值中哪些值符合我的标准,就像这样。

int [] array;
int arraysize;
int lowvalue;
int total;

for(int i = 0; i<arraysize; ++i)
{
    if(array[i] == lowvalue*1.05) ++total;
}

我的问题是在数组中获取这些值。我已阅读this但 d+ 并不真正适用于浮点。

最佳答案

您应该使用正则表达式:

Regex r = new RegEx("[0-9]+\.[0-9]+");
Match m = r.Match(myString);

类似这样的事情。然后你就可以使用:

float f = float.Parse(m.value);

如果你需要一个数组:

MatchCollection mc = r.Matches(myString);
string[] myArray = new string[mc.Count];
mc.CopyTo(myArray, 0);

编辑

我刚刚为你创建了一个小示例应用程序,乔。我编译了它,并且使用您问题中的输入行在我的机器上运行良好。如果您遇到问题,请发布您的输入字符串,以便我可以尝试一下。这是我写的代码:

static void Main(string[] args)
{
    const string InputString = "Item X $4.50 Description of item \r\n\r\n Item Z $4.75";

    var r = new Regex(@"[0-9]+\.[0-9]+");
    var mc = r.Matches(InputString);
    var matches = new Match[mc.Count];
    mc.CopyTo(matches, 0);

    var myFloats = new float[matches.Length];
    var ndx = 0;
    foreach (Match m in matches)
    {
        myFloats[ndx] = float.Parse(m.Value);
        ndx++;
    }

    foreach (float f in myFloats)
        Console.WriteLine(f.ToString());

    // myFloats should now have all your floating point values
}

关于c# - 在大字符串中查找浮点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6754545/

相关文章:

C# 使用多线程或并行执行执行 SQL SP

Java/MySQL 对正则表达式查询很奇怪

C:使用指针时如何分配内存?

c - 如何确定字符串长度?

c# - 我应该使用 SqlDataReader 还是 SqlDataAdapter 类来返回数据表

c# - 从azure openai sdk api返回流的正确方法

c# - 图像按钮的单击事件

python - Pandas - 获取 pandas 数据框列括号内的值

ruby:使用正则表达式将 http://anything 替换为 <a href ="http://anything">http://anything</a>

python - Django,检测变量是否为数字