1

I have code like:

(00)1234567891234(10)1234(3100)12315

Code in brackets are standard names and are always the same. But order can be different. (10) can be before (00) and instead of (3100) can be (01)

What is the best solution to pars data like:

(00)1234567891234
(10)1234
(3100)12315

and then if i write

00 i will get 1234567891234

10 i will get 1234

3100 i will get 12315

what is the best aproach for doing this and how? How can i get value between ()xx()?

6
  • 2
    What have you tried? It is also not clear if the data has line breaks between key-value pairs or not. Commented Dec 5, 2011 at 12:50
  • i try with indexOf which is bad idea. code has no line breaks. Commented Dec 5, 2011 at 12:52
  • 2
    Have you looked at String.Split? Commented Dec 5, 2011 at 12:52
  • i was looking split yes but i am bad with regex Commented Dec 5, 2011 at 12:56
  • String.Split doesn't use RegEx. Commented Dec 5, 2011 at 12:57

3 Answers 3

3

Try this

    const string text = "(00)1234567891234(10)1234(3100)12315";

    var result =  Regex.Matches(text, @"\((\d+)\)(\d+)").Cast<Match>()
        .Select(x => new {Value = x.Groups[2].Value, Key = x.Groups[1].Value})
        .ToDictionary(y => y.Key, x => x.Value);

    foreach (var r in result)
    {
        Console.WriteLine("Key: {0}, Value: {1}", r.Key, r.Value);
    }


    /* OUTPUT
     * 
     *  Key: 00, Value: 1234567891234
        Key: 10, Value: 1234
        Key: 3100, Value: 12315
     */

    Console.Read();

Using Linq (which seems to be preferable here) in one line you get a Dictionary<string, string> with an object that has two properties Key and Value.

Sign up to request clarification or add additional context in comments.

1 Comment

very nice! I like the approach!
1

Very simple approach:

string input = "(00)1234567891234(10)1234(3100)12315";
string[] lines = input.Split(new [] {"("}, StringSplitOptions.RemoveEmptyEntries);
foreach(string ln in lines)
{
    string key = ln.Substring(0, ln.IndexOf(')'));
    string value = ln.Substring(ln.IndexOf(')') + 1);
}

Comments

1

I won't write code for you but will give you a hint

(00)1234567891234(10)1234(3100)12315

parse above string based on ( and this ) you can use String.Split method for this

this will give you following in a array

00
1234567891234
10
1234
3100
12315

Now you can pair these value and put them in a Dictionary<String, String>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.