【问题标题】:Why is this string only returned one time when using LINQ vs Regex? [closed]为什么在使用 LINQ 和 Regex 时这个字符串只返回一次? [关闭]
【发布时间】:2016-05-11 15:07:35
【问题描述】:

编辑: 我应该澄清一下,但我正在 Visual Studio 中调试这两个应用程序。因此,当我部署它时,一个转到 Rasp Pi(这是有问题的应用程序),另一个是在我的本地计算机上运行的控制台应用程序。

我不知道该如何表达这个问题,但在您的帮助下,我相信我可以将它变成一个更通用的问题。 此时我的项目正在运行,但我不确定为什么我之前实现此字符串解析的方式不起作用。我想知道为什么。

设置:

我有一个控制台应用程序,我可以将命令写入其中,并将其发送到 IoT 中心,然后我的 Raspberry Pi 读取、解析命令并执行函数。

        // Keep listening for messages            
        private async Task listenForMessageFromDeviceTask()
        {
            while (true)
            {
                var msg =  await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                if (msg == null) continue;

                Globals.ParseMsg(msg);
            }
        }

解决方案:

Link to the current working class on GitHub

public static void ParseMsg(string msg)
{
    // Split msg on whitespace sequences. 
    // This works great! I only need to retrieve the first word.
    string[] firstWordInMsg = Regex.Split(msg, @"\s+");

        switch (firstWordInMsg[0])
        {
            case "tween":
                // Do something
                break;
            case "stop":
                // Do something
                break;
        }

问题:

Link to the non-working version on GitHub

public static void ParseMsg(string msg)
{
    // This will only execute ONE time. I can send 10 messages, and it will
    // only receive one. I now have to restart the app, and it can then                  // receive the next message in the queue.
    var first_word = FirstWordFromMessage(msg)

    switch (first_word)
    {
        case "tween":
            // Do something
            break;
        case "stop":
            // Do something
            break;
    }


    public string FirstWordFromMsg(string msg)
    {
    var firstWord = msg.Substring(0, msg.IndexOf(" ", StringComparison.Ordinal));

    return firstWord;
  }

我的理解: 当我使用第一个解决方案时,一切都很好。我可以发送 10 条消息,应用程序可以读取全部 10 条消息。

使用第二种实现方式,我只能在需要重新启动应用程序之前阅读一条消息。在这一点上,它还有9个要通过。然后我需要退出应用程序,重新启动它,然后它还有 8 次要完成。

为什么会这样?

【问题讨论】:

  • 您能否为您的应用创建一个可重现的最小示例?
  • 如果字符串不包含空格,您的第二种方法将引发异常。
  • 不清楚你在这里得到什么。 “在我需要重启应用之前”你在调试它吗??
  • 是的@Liam,我应该清楚我正在调试它。

标签: c# regex string linq


【解决方案1】:

您需要遍历words 中包含的每条消息:

public static void ParseMsg(string msg)
{
    string[] words = Regex.Split(msg, @"\s+");

    foreach (string word in words)
    {
        switch (word)
        {
            case "tween":
                // Do something
                break;
            case "stop":
                // Do something
                break;
        }
    }
}

【讨论】:

  • 我明白,如果我需要获取每个单词,这将是正确的方法。就目前而言,我只需要第一个单词,所以我的底部示例可以正常工作。但是,我不确定为什么我提供的第一个解决方案不起作用。不过,谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2019-10-06
  • 1970-01-01
相关资源
最近更新 更多