在c#中的某个单词之后/之前过滤字符串中的值

时间:2011-09-01 09:58:19

标签: c# .net string

我有很长的字符串,这是来自IMAP请求的响应,我想从中提取一些值。它通常被格式化为“x someword”或“someword x” - 如何得到x(它可以超过一个数字)的某个词(已知)?每个响应的“线”看起来像:

* x someword \r\n

我的字符串包含几行。提取所需值的最简单方法是什么?

实施例: for“* x word1 \ r \ n * y word2 \ r \ n”,word2作为参数我想得到y

整个回复示例:

* FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen)\r\n* OK [PERMANENTFLAGS ()] Flags permitted.\r\n* OK [UIDVALIDITY xxx] UIDs valid.\r\n* 3 EXISTS\r\n* 0 RECENT\r\n* OK [UIDNEXT x] Predicted next UID.\r\n. OK [READ-ONLY] INBOX selected. (Success)\r\n

对于“EXISTS”我想得到3。

5 个答案:

答案 0 :(得分:1)

所以给出: X markerWord \ n \ rmarkerWord Y

你想要{X,Y}吗? 如果是这样,请先尝试按行分割,然后只需删除“markerWord”。

大致类似于:

var result = input.Split(new[]{'\n', '\r'}).Select(line => line.Replace("markerWord", string.Empty);

更新的答案: 那么我会使用正则表达式。简单的概念证明,我相信你可以从这里拿走它:

static string GetParam(string input, string param) {
            var pattern = new Regex(@"[\\*](?<value>.+)" + param);
            var split = input.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            var line = split.SingleOrDefault(l => pattern.IsMatch(l));
            if(line != null) {
                return pattern.Match(line).Groups["value"].Value.Trim();
            }
            return null;
        }

答案 1 :(得分:1)

我会使用正则表达式...这是你可以做的:

string myString = "* FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen)\r\n* OK [PERMANENTFLAGS ()] Flags permitted.\r\n* OK [UIDVALIDITY 657136382] UIDs valid.\r\n* 3 EXISTS\r\n* 0 RECENT\r\n* OK [UIDNEXT 4] Predicted next UID.\r\n. OK [READ-ONLY] INBOX selected. (Success)\r\n";

string myWordToFind = "EXISTS";

string result = Regex.Match(myString, @"(?<MyNumber>\d+)\s*(" + Regex.Escape(myWordToFind) + ")",
    RegexOptions.Compiled | RegexOptions.IgnoreCase)
    .Groups["MyNumber"].Value;

答案 2 :(得分:1)

class Class1
{
     string str = "* FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen)\r\n* OK [PERMANENTFLAGS ()] Flags permitted.\r\n* OK [UIDVALIDITY 657136382] UIDs valid.\r\n* 3 EXISTS\r\n* 0 RECENT\r\n* OK [UIDNEXT 4] Predicted next UID.\r\n. OK [READ-ONLY] INBOX selected. (Success)\r\n";

     public void FindString(string parm)
     {
         if (str.Contains(parm))
         {
             string[] parts = str.Split('*');
             foreach (var item in parts)
             {
                 if (item.Contains(parm))
                 {
                     string[] values = item.Split(' ');
                     string value = values[1];
                 }
             }
         }
     }

     static void Main(string[] args)
     {
         Class1 c = new Class1();
         c.FindString("EXISTS");
     }
}

答案 3 :(得分:1)

你应该使用正则表达式

Regex r=new Regex(@"(?<value>\d+)\s*(?<keyword>EXISTS|RECENT)");

foreach (var match in r.Matches(source).OfType(Match)) {
  var parameter=int.Parse(match.Groups["value"].Value);
  switch (match.Groups["keyword"].Value) {
    case "EXISTS":
      doExists(parameter);
      break;
    case "RECENT":
      doRecent(parameter);
      break;
  }
}

答案 4 :(得分:1)

您可以使用以下(希望是不言自明的)代码:

const string response =@"
    * FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen)
    * OK [PERMANENTFLAGS ()] Flags permitted.
    * OK [UIDVALIDITY 657136382] UIDs valid.
    * 3 EXISTS
    * 0 RECENT
    * EXISTS 4      <------------------- another occurence of the word
    * OK [UIDNEXT 4] Predicted next UID.
    * OK [READ-ONLY] INBOX selected. (Success)";

    string word = "EXISTS";
    string pattern =
        Regex.Escape(word) +  // the word to find followed by...
        @"
        \s+         (?# one ore more space characters followed by... )
        (?<num>\d+) (?# one or more digits. )

        |           (?# Or )

        (?<num>\d+) (?# one or more digits, then... )
        \s+         (?# one ore more space characters followed by... )"
        + Regex.Escape(word); // the word to find.

    foreach (Match match in Regex.Matches(response, pattern, RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace))
    {
        Console.WriteLine(match.Groups["num"]);
    }