0

i wonder to know how to split specific string from message the user sent the message looks like this

"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

what exacly i meant is to get the 9 digits after "uid:" ?

thank you very much ! i found a simmilar questions but none of the anwered to my question sorry for the spelling my english is not native

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
tuarek
  • 69
  • 1
  • 8
  • 1
    Could you, please, provide *some examples*: initial string(s) and the desired outcome(s), say `"username @me\r\npassword: 123\r\nmnumer: 123456789" -> ("me", "123456789")` – Dmitry Bychenko Sep 07 '18 at 11:18
  • all the code section in my question is the string im reciving from what i want to do is to split from it the values that i mention in the code section – tuarek Sep 07 '18 at 11:22
  • Is it one long string, like what @DmitryBychenko posted, or multiple strings? i.e. `string userName = "username :@newbie"`, `string passWord = "password: 1g1d91dk"`, etc. – eye_am_groot Sep 07 '18 at 11:25
  • its one long string thats what im trying to say i want to recive the separtely not togther – tuarek Sep 07 '18 at 11:26
  • Come on guys, lets not be rude here, you can see he's new and I've managed to understand what he means... – Zach Ross-Clyne Sep 07 '18 at 11:30
  • @ZachRoss-Clyne Who is being rude? – Fildor Sep 07 '18 at 11:31
  • @ZachRoss-Clyne the distinction between what the initial string(s) is(are) is definitely important (and unclear imho at the start). Just seeking clarification :-) – eye_am_groot Sep 07 '18 at 11:33
  • 1
    @Greg, Fildor, it was mainly Tim being rude. – Zach Ross-Clyne Sep 07 '18 at 11:43
  • @ZachRoss-Clyne Then read some Comments of really old questions ... Comments sometimes may seem rude but that's because you can transport emotion really badly in them. If what Tim wrote seems "rude" to you, you need to 1) grow thicker skin, 2) just assume it wasn't _meant_ to be rude if in doubt. Don't get me wrong: I am 100% pro "be nice" - but we have to keep it reasonable. – Fildor Sep 07 '18 at 12:09
  • @Fildor I never took it personally, I just thought it may have been worded differently as OP is such a new member to SO. – Zach Ross-Clyne Sep 07 '18 at 12:28
  • @ZachRoss-Clyne That's ok. I think I am just not that sensitive ... – Fildor Sep 07 '18 at 12:43

4 Answers4

2

Could you not simply split the string by new line .Split('\n') which will give you a string[] and then in each element split that by ':' and then read the second value? You could store this in a Dictionary<string, string> if you need to reference by the first bit

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());
}

This will give you a dictionary where you can access the value of each part of the string by the first part.

Not sure what your usage is but that will help.

You can get the uid by doing data["uid"]

Zach Ross-Clyne
  • 779
  • 3
  • 10
  • 35
  • What if message contains ":" ? – Fildor Sep 07 '18 at 11:30
  • That's a good point. I'll edit – Zach Ross-Clyne Sep 07 '18 at 11:30
  • 1
    `string[] keyValue = line.Split(new char[] {':'}, 2);` in this case `message` can well have `:` (we split on the *1st* `:` only) – Dmitry Bychenko Sep 07 '18 at 11:31
  • I like your way better I will put in both options – Zach Ross-Clyne Sep 07 '18 at 11:32
  • Rather than splitting on ":", I think it would be better to check whether each line starts with each of the possible fields ("Username:", "Password", "message:", etc) and handle each one. That could handle multiple line messages, and ":" in the middle of the message. – Robin Bennett Sep 07 '18 at 11:32
  • @Robin A message could contain a line that starts with one of the keywords, right? – Fildor Sep 07 '18 at 11:33
  • 1
    I was considering about the multi line messages but as @Fildor pointed out a line could start with a keyword. Also OP hasn't said whether a message can be multiple lines or not. – Zach Ross-Clyne Sep 07 '18 at 11:35
  • I agree that it seems to be supposed to be single-line messages. But OP did not explicitly make that clear. So, it would be good to have him answer that. – Fildor Sep 07 '18 at 11:37
  • Also, given the message doesn't have quotes around it, lets suppose the end of the message was `word: word` then because of no quotes this would get picked up as a seperate thing instead. I agree, OP needs to clarify – Zach Ross-Clyne Sep 07 '18 at 11:46
  • @Fildor, yes, lines starting with keywords could (potentially) occur multiple times and that's a problem with any type of string parsing. (it would cause errors if you're just adding them to a dictionary). With my method, you'd know you're in the middle of the message, and could safely ignore keywords that you've already seen. Ideally you'd always put the message at the end, or have an EndOfMultilineField keyword, or some way to indicate the length of the field. – Robin Bennett Sep 07 '18 at 11:58
  • 1
    @RobinBennett ... like a decent protocol :) – Fildor Sep 07 '18 at 12:04
1

Try using regular expressions:

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;

In case uid: should start the line

string result = Regex.Match(
   source, 
 @"(?<=^uid:\s*)[0-9]{9}", 
   RegexOptions.Multiline).Value;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can use regular expressions to match a pattern in a text value, and get the desired values. For example, try this :

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

A similar approach to @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;
        }

    }
}
spender
  • 117,338
  • 33
  • 229
  • 351
  • Why not `.Split(new char[] { '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries` instead of `.AsLines()`? – Dmitry Bychenko Sep 07 '18 at 11:38
  • `using (StringReader sr = ...) {...}` since StringReader implements `IDisposable` – Dmitry Bychenko Sep 07 '18 at 11:39
  • @DmitryBychenko Why not `Regex.Split(data, @"\r?\n")` or any number of ways to do the same thing? I concur about the `StringReader`, although I'd bet my house that the dispose method does nothing. – spender Sep 07 '18 at 11:43
  • 1
    @DmitryBychenko Looks like I [just lost my house](https://github.com/dotnet/corefx/blob/master/src/System.Runtime.Extensions/src/System/IO/StringReader.cs#L33) :) . Perhaps I should have said "nothing meaningful in the context of this code". – spender Sep 07 '18 at 11:51
  • @spender " Looks like I just lost my house" - I guess you should avoid Las Vegas ... :D – Fildor Sep 07 '18 at 12:12