【问题标题】:How do I use string.StartsWith() when I only have some parts of the comparison string?当我只有比较字符串的某些部分时,如何使用 string.StartsWith()?
【发布时间】:2013-08-15 12:43:05
【问题描述】:

我正在使用 IRC 协议,并且正在尝试解释服务器消息。例如,如果我得到以下字符串:

":USERNAME!~IP PRIVMSG #CHANNELNAME :MESSAGE"

如果我不知道变量:USERNAME、IP、CHANNELNAME 或 MESSAGE,我该如何使用 string.StartsWith?

我想做这样的事情:(我知道这行不通)

if(MessageString.StartsWith(":*!~* PRIVMSG #*"))

【问题讨论】:

  • 这是正则表达式的工作。 msdn.microsoft.com/en-us/library/hs600312.aspx
  • 你应该看看正则表达式
  • 你有例子吗?
  • @Robin 如果您在 Google 上搜索“正则表达式教程”,您可能会自己找到很多资源,现在您知道自己在寻找什么了 :)
  • 我知道正则表达式是什么,我知道在做其他事情时如何使用它们。但是我不知道这个特定问题的术语是什么,只搜索“正则表达式教程”会给我更多我需要的信息。

标签: c# .net string startswith


【解决方案1】:

我不会使用 StartsWith。我建议通过例如解析字符串将其拆分为令牌。这样您就可以检查 PrivMsg 字符串是否包含在令牌列表中。

可能有已经准备好解析 IRC 消息的库。你查过https://launchpad.net/ircdotnet吗?

【讨论】:

    【解决方案2】:

    您可以尝试使用正则表达式:

    http://msdn.microsoft.com/en-us/library/az24scfc.aspx

      // Check this regular expression: 
      // I've tried to reconstruct it from wild card in the question 
      Regex regex = new Regex(@":.*\!~.* PRIVMSG \#.*");
    
      Match m = regex.Match(":USERNAME!~IP PRIVMSG #CHANNELNAME :MESSAGE");
    
      if (m.Success) {
        int startWith = m.Index;
        int length = m.Length;
        ...
      }
    

    【讨论】:

      【解决方案3】:

      尝试这样的事情,使用 Regex 类。

      var regex = new Regex(
          @":(?<userName>[^!]+)!~(?<ip>[^ ]+) PRIVMSG #(?<theRest>[\s\S]+)");
      var match = regex.Match(MessageString);
      if (match.Success)
      {
          var userName = match.Groups["userName"].Value;
          var ip = match.Groups["ip"].Value;
          var theRest = match.Groups["theRest"].Value;
      
          // do whatever
      }
      

      我还会看看 .Net 中的 MSDN page for regular expressions。

      【讨论】:

        【解决方案4】:

        尝试在您不知道的单词后面使用分隔符,并从只包含消息的主要单词中解析一个字符串。

        【讨论】:

        • 我......甚至无法说出这应该是什么意思。我得到的只是“解析它”,这甚至还没有接近答案。
        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 2023-03-11
        • 2010-09-17
        • 2018-06-05
        • 2016-12-27
        • 1970-01-01
        • 2013-08-10
        • 2011-12-31
        相关资源
        最近更新 更多