【问题标题】:How to extract string using C# [closed]如何使用 C# 提取字符串 [关闭]
【发布时间】:2012-12-17 15:10:10
【问题描述】:

我需要从下面给出的文本中提取以粗体显示的密码值 (Password10)。我正在使用 c# 编程语言。

FName Lname,您的系统密码已更改。如果您没有更改或不知道更改原因,请立即联系管理员。您的新密码是Password10

如果您有任何问题,请联系:

解决方案项目办公室 电话: 邮箱:notifications@cho.com

感谢您使用 xxxxx

【问题讨论】:

  • 前几天有人贴了这个链接,我认为这很适合这种特殊情况:whathaveyoutried.com
  • 将整个内容作为字符串读入,将“if you have..”开头的部分剪掉。从“password is”结尾(应该始终是相同的起始索引)到新字符串结尾的子字符串。
  • 文本是字符串吗? string j = mystring.Remove(0, mystring.LastIndexOf(" ")); 编辑,在代码大纲之前发布,删除仍然可以工作,只是不是这样
  • 如果是具有类人类保护的富文本格式字符串怎么办? "仔细阅读。密码在 END 中最后一个字母之后的第 5 个符号处。所以 Password10 是非常不快的。您的密码是:无可用的。"

标签: c# text-extraction


【解决方案1】:

好吧,如果您确定这将是文本的呈现形式。总是。然后您可以简单地执行以下操作:

string text = //load your text here;
int startingIndex = text.IndexOf("Your new password is ") + "Your new password is ".Length;
string newText = text.SubString(startingIndex, text.length); //this will load all your text after the password.
//then load the first word
string password = newText.Split(' ')[0];

【讨论】:

  • 密码为粗体,后面没有魔术字符序列
  • 后面是一个空格:)
【解决方案2】:

您也可以考虑使用 RegEx(正则表达式)。

【讨论】:

    【解决方案3】:

    你可以使用string.Substring:

    int indexOfPasswordText = text.IndexOf("Your new password is ");
    if (indexOfPasswordText != -1)
    {
        int passwordStart = indexOfPasswordText + "Your new password is ".Length;
        int indexeOfNextWord = text.IndexOfAny(new[] { '\n', '\r', ' ' }, passwordStart);
        if (indexeOfNextWord == -1) indexeOfNextWord = text.Length;
        string passWord = text.Substring(passwordStart, indexeOfNextWord - passwordStart);
        Console.Write(passWord);
    }
    

    Demo

    【讨论】:

      【解决方案4】:

      我没有对此进行测试,但也许它可以将您推向正确的方向。

      string input = [YOUR MAIL];
      string regex = @"Your new password is (\w+)";
      Match m = Regex.Match(input, regex);
      if (m.Success) {
          string password= m.Groups[1].Value;
          //do something
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 1970-01-01
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        • 2020-07-12
        • 1970-01-01
        • 1970-01-01
        • 2011-01-19
        相关资源
        最近更新 更多