Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a string content with some keywords and values. I want to get value follow the keyword.

C#
string _str = "{ Text = Banana, Value = 81 }";
//string _strText = "Banana";
//string _strValue = "81";


How can I parse it and get value by keyword?

What I have tried:

I'm not sure, but I guess I should convert to some object and get value by keyword.
Posted
Updated 21-Aug-23 12:16pm
v2
Comments
PIEBALDconsult 14-Aug-23 12:16pm    
Regular Expressions.
Using a Regular Expression yields a MatchCollection, after which you can then access the Groups by name.
As to: "should convert to some object and get value by key word" -- that really just restates the problem and maybe even moves the goal post.

If possible, use a better-supported format, such as JSON or XML.

I will use regular expressions to match the key-value pairs in your input string, others might disagree with me. :)

I have created a fiddle for you at - Reading string values in C#[^]

C#
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string _str = "{ Text = Banana, Value = 81 }";

        //Define the keywords you want to extract...
        string keywordText = "Text";
        string keywordValue = "Value";

        //Use regular expressions to extract the values...
        string textValue = ExtractValue(_str, keywordText);
        string valueValue = ExtractValue(_str, keywordValue);

        //Output the extracted values...
        Console.WriteLine("Text: " + textValue);
        Console.WriteLine("Value: " + valueValue);
    }

    public static string ExtractValue(string input, string keyword)
    {
        //Construct the regular expression pattern...
        string pattern = @"\b" + keyword + @"\s*=\s*([^,}]+)";

        //Match the pattern in the input string...
        Match match = Regex.Match(input, pattern);

        //Extract the value from the match...
        string value = match.Success ? match.Groups[1].Value.Trim() : null;

        return value;
    }
}


The output -
Output
Text: Banana
Value: 81
 
Share this answer
 
Comments
headshot9x 15-Aug-23 4:47am    
Hi, I learned more in this case with Regex expression.
Andre Oosthuizen 15-Aug-23 8:32am    
You're welcome, I glad it helped you.

Here is a simplistic approach


C#
static void Main(string[] args)
      {
          string str = "{ Text = Banana, Value = 81,Text = Apple, Value = 11,Text = Orange, Value = 21 }";
          //Convert to KeyValue pairs eg. Banana:81
          var kvps = str.Trim('{', '}').Replace(" ", "").Replace("Text=", "").Replace(",Value=", ":").Split(',');
          //Output them as required.
          foreach (var kvp in kvps)
          {
              var values = kvp.Split(":");
              Console.WriteLine($"Text= {values[0]} Value={values[1]}");
          }

          Console.ReadLine();
      }

Edit


In view of the comment that this method is very inefficient, it may be helpful to show the BenchmarkDotNet test results for processing a test string formatted as in the example. The test method extracted 1000 key value pairs from a single string in a mean time of 0.2056 milliseconds with an allocated memory use of 210.55KB


BenchmarkDotNet=v0.12.1, OS=Windows 10.0.22621
Intel Core i7-8565U CPU 1.80GHz (Whiskey Lake), 1 CPU, 8 logical and 4 physical cores
| Method | Mean     | Error   | StdDev  | Ratio | Rank | Gen 0   | Gen 1  | Gen 2 | Allocated |
|------- |---------:|--------:|--------:|------:|-----:|--------:|-------:|------:|----------:|
| DoWork | 205.6 us | 4.01 us | 7.12 us | 1.00  | 1    | 51.2695 | 0.2441 | -     | 210.55 KB |
 
Share this answer
 
v2
Comments
headshot9x 15-Aug-23 4:45am    
Hi, It's look the best idea.
PIEBALDconsult 15-Aug-23 10:28am    
It is very inefficient.
George Swan 15-Aug-23 11:40am    
You may well be correct but it gets the job done in a few lines of code and it is easy to understand.
PIEBALDconsult 15-Aug-23 12:31pm    
I would assume that a string with multiple name/value pairs would be more like this, but the OP needs to provide such detail:
string str = "{ Text = Banana, Value = 81}, { Text = Apple, Value = 11}, { Text = Orange, Value = 21 }";
George Swan 15-Aug-23 13:07pm    
Yes, it would be ideal to have a Json string and then System.Text.Json could do the heavy lifting
Here's a simple lookup table class which might be instructive:

C#
public sealed partial class LookupTable : System.IDisposable
{
  private static readonly System.Text.RegularExpressions.Regex reg ;

  static LookupTable
  (
  )
  {
    reg = new System.Text.RegularExpressions.Regex
    (
      @"\{\s*Text\s*=\s*(?'Name'\S+)\s*,\s*Value\s*=\s*(?'Value'\S+)\s*\}"
    ,
      System.Text.RegularExpressions.RegexOptions.Compiled
      |
      System.Text.RegularExpressions.RegexOptions.IgnoreCase
    ) ;

    return ;
  }

  private readonly System.Collections.Generic.Dictionary<string,string> dic ;

  public LookupTable
  (
    string Data
  )
  {
    this.dic = new System.Collections.Generic.Dictionary<string,string>
    (
      System.StringComparer.InvariantCultureIgnoreCase
    ) ;

    System.Text.RegularExpressions.MatchCollection mat = reg.Matches
    (
      Data
    ) ;

    for ( int i = 0 ; i < mat.Count ; i++ )
    {
      System.Text.RegularExpressions.Group nam = mat [ i ].Groups [ "Name"  ] ;
      System.Text.RegularExpressions.Group val = mat [ i ].Groups [ "Value" ] ;

      this.dic [ nam.Value ] = val.Value ;
    }

    return ;
  }

  public void
  Dispose
  (
  )
  {
    this.dic.Clear() ;

    return ;
  }

  public bool
  TryGetValue
  (
    string     Name
  ,
    out string Value
  )
  {
    return ( this.dic.TryGetValue ( Name , out Value ) ) ;
  }
}
 
Share this answer
 
Comments
headshot9x 15-Aug-23 4:49am    
Hi, probably we need more setup on that ?. Anyway, this is usefully to learn, thanks a lot.
PIEBALDconsult 15-Aug-23 10:30am    
Maybe. We would need to know how additional name/value pairs may be specified.
Is there no way to use a proper JSON format instead?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900