Home > database >  c# search string containing name/value pairs
c# search string containing name/value pairs

Time:05-06

I'm looking for an efficient way to search a string of name value pairs. Specifically for an instance whereby the value of one of the items is empty. For instance, given the following examples I want to know if val2 is empty:

"val1=aa,val2=bb,val3=cc"  // should return false
"val1=aa,val2=,val3=cc"   // should return true
"val1=aa,val2=   ,val3=cc" // should return true

what would be a most efficient way to do this perhaps using linq or Regex or some other means?

Thanks!

CodePudding user response:

You can do this with string.Split() and string.IsNullOrWhiteSpace():

//uncomment the line you want to check
string s = "val1=aa,val2=bb,val3=cc";
//string s = "val1=aa,val2=,val3=cc";
//string s = "val1=aa,val2=   ,val3=cc";

string[] sarr = s.Split(',');

bool hasBlank = false;

foreach (string str in sarr)
    if (string.IsNullOrWhiteSpace(str.Substring(5, str.Length - 5)))
        hasBlank = true;

Console.WriteLine(hasBlank);

We split the key/value pairs with string.Split(), then iterate through those to get the value via string.Substring(). I'm operating under the assumption that the key will always be 5 characters including the =. If not, you can do additional calculations to get the starting point.

After we have gotten the value, we simply check it for blanks with string.IsNullOrWhiteSpace().

However, I would recommend you change these to another data type that is better suited to handling key/value pairs.

CodePudding user response:

Here is one way to do so using Regex:

val2=([^,]*)
  • val2=: Matches val2=
  • (): First capturing group
    • [^,]*: Any character other than ,, between zero and unlimited times.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string pattern = @"val2=([^,]*)";
        string input = @"val1=aa,val2=bb,val3=cc";
        
        Match m = Regex.Match(input, pattern);
        
        Console.WriteLine(string.IsNullOrWhiteSpace(m.Groups[1].Value));
    }
}
  • Related