当我只有比较字符串的某些部分时,如何使用string.StartsWith()?

时间:2013-08-15 12:43:06

标签: c# .net string startswith

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

“:USERNAME!~IP PRIVMSG #CHANNELNAME:MESSAGE”

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

我想做这样的事情:(我知道这不起作用)

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

4 个答案:

答案 0 :(得分:2)

我不会使用StartsWith。我建议通过例如解析字符串把它分成代币。这样你可以检查PrivMsg字符串是否包含在token-List中。

可能还有库已经解析了IRC消息。你检查过https://launchpad.net/ircdotnet吗?

答案 1 :(得分:1)

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

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;
    ...
  }

答案 2 :(得分:0)

使用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

答案 3 :(得分:-1)

尝试在您不知道的单词之后使用分隔符,并解析仅包含该消息的主字符串中的字符串。