【问题标题】:get part of string/digits after specific char in C# [duplicate]在C#中的特定字符之后获取部分字符串/数字[重复]
【发布时间】:2019-02-12 17:49:37
【问题描述】:

我想知道如何从用户发送的消息中拆分特定字符串 消息看起来像这样

"username: @newbie <----- need to recive the all string with the '@'
password: 1g1d91dk
uid: 961515154 <-- always string of 9 numbers
message: blablabla < ---- changing anytime how can i recive the string after message:"
date: 30/06/18" 
mnumer: 854762158 <-- always string of 9 numbers to but i want to upper one

我的意思是在 "uid:" 之后得到 9 digits

非常感谢! 我发现了一个类似的问题,但没有一个回答我的问题 对不起,我的英语不是母语的拼写

【问题讨论】:

  • 能否请您提供一些示例:初始字符串和期望的结果,例如"username @me\r\npassword: 123\r\nmnumer: 123456789" -&gt; ("me", "123456789")
  • 我的问题中的所有代码部分都是我想要做的就是从中拆分出我在代码部分中提到的值
  • 是一个长字符串,就像@DmitryBychenko 发布的那样,还是多个字符串?即string userName = "username :@newbie"string passWord = "password: 1g1d91dk"
  • 它的一个长字符串就是我想说的,我想单独接收而不是一起
  • @Greg,Fildor,主要是 Tim 粗鲁。

标签: c# string


【解决方案1】:

你能不能简单地用新行.Split('\n')分割字符串,这会给你一个string[],然后在每个元素中用':'分割,然后读取第二个值?如果您需要通过第一位引用,您可以将其存储在 Dictionary&lt;string, string&gt;

string inString = @"username: @newbie
password: 1g1d91dk
uid: 961515154
message: blablabla
date: 30/06/18
mnumer: 854762158";

string[] lines = inString.Split('\n');

Dictionary<string, string> data = new Dictionary<string, string>();

foreach (string line in lines)
{
    // There are two ways to avoid splitting multiple : and just using the first
    // Here is my way
    string[] keyValue = line.Split(':');

    data.Add(keyValue[0].Trim(), string.Join(':', keyValue.Skip(1).ToArray()).Trim());

    // Here is another way courtesy of: Dmitry Bychenko
    string[] keyValue = line.Split(new char[] {':'}, 2);

    data.Add(keyValue[0].Trim(), keyValue[1].Trim());
}

这将为您提供一个字典,您可以在其中通过第一部分访问字符串每个部分的值。

不确定您的用途是什么,但这会有所帮助。

你可以通过data["uid"]获得uid

【讨论】:

  • 如果消息中包含“:”怎么办?
  • 这是一个很好的观点。我会编辑
  • string[] keyValue = line.Split(new char[] {':'}, 2); 在这种情况下 message 可以有 : (我们只在 1 日 : 分裂)
  • 我正在考虑多行消息,但正如@Fildor 指出的那样,一行可以以关键字开头。 OP也没有说明消息是否可以是多行。
  • @RobinBennett ...就像一个体面的协议:)
【解决方案2】:

您可以使用正则表达式来匹配文本值中的模式,并获得所需的值。例如,试试这个:

var regex = new Regex(@"^(uid:\s)([0-9]+)");
var match = regex.Match("uid: 961515154");
Console.WriteLine(match.Groups[1].Value); // you should get : 961515154

【讨论】:

    【解决方案3】:

    尝试使用正则表达式

    string source = 
    @"username: @newbie <----- need to recive the all string with the '@'
    password: 1g1d91dk
    uid: 961515154 <-- always string of 9 numbers
    message: blablabla < ---- changing anytime how can i recive the string after message:"
    date: 30/06/18" 
    mnumer: 854762158 <-- always string of 9 numbers to but i want to upper one";
    
    
    string result = Regex.Match(source, @"(?<=uid:\s*)[0-9]{9}").Value;
    

    如果uid: 应该开始该行

    string result = Regex.Match(
       source, 
     @"(?<=^uid:\s*)[0-9]{9}", 
       RegexOptions.Multiline).Value;
    

    【讨论】:

      【解决方案4】:

      与@ZachRossClyne 类似的方法:

      void Main()
      {
          var data = @"username: @newbie
                      password: 1g1d91dk
                      uid: 961515154
                      message: blablabla
                      date: 30 / 06 / 18
                      mnumer: 854762158";
      
          var regex = new Regex(@"^\s*(?<key>[^\:]+)\:\s*(?<value>.+)$");
          var dic = data
              .AsLines()
              .Select(line => regex.Match(line))
              .Where(m => m.Success)
              .Select(m => new { key = m.Groups["key"].Value, value = m.Groups["value"].Value })
              .ToDictionary(x => x.key, x => x.value);
          Console.WriteLine(dic["uid"]);
      }
      
      public static class StringEx
      {
          public static IEnumerable<string> AsLines(this string input)
          {
              string line;
              using(StringReader sr = new StringReader(input))
              while ((line = sr.ReadLine()) != null)
              {
                  yield return line;
              }
      
          }
      }
      

      【讨论】:

      • 为什么不用.Split(new char[] { '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries 而不是.AsLines()
      • using (StringReader sr = ...) {...} 因为 StringReader 实现了IDisposable
      • @DmitryBychenko 为什么不Regex.Split(data, @"\r?\n") 或任何数量的方式来做同样的事情?我同意StringReader,尽管我敢打赌 dispose 方法什么都不做。
      • @DmitryBychenko 看起来像我 just lost my house :) 。也许我应该说“在这段代码的上下文中没有任何意义”。
      • @spender "看起来我刚刚失去了我的房子" - 我想你应该避开拉斯维加斯......:D
      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2022-01-18
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多