Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Hi,

How to find if
C#
"join"
text contains only inside Value, not consider Key?

What I have tried:

C#
public bool IsValid()
        {
            string val = "join";
            bool isNotValid = false;
            string jsondata = "{"Id":null,"FName":"Vicky","LName":"Denny","DateofJoining":null,"Date":"2023 - 08 - 01T00: 00:00","CreatedBy":"ICC0000389"}";

            if (jsondata.ToUpper().Contains(val.ToUpper()))
            {
                isNotValid = true;

            }
            return isNotValid;
        }


This line of code
C#
if (jsondata.ToUpper().Contains(val.ToUpper()))
finding "join" from all jsondata. Instead of, how can I find the word from value only?

Thanks
Posted
Updated 9-Aug-23 10:58am
v2

The best way is to use something like Newtonsoft Json.NET[^] to read the whole Json into "sensible" classes and process those, but it could be done with a Regex:
RegEx
(?<Key>".*?":)(("(?<Value>.*?)")|(null))
Will extract all the Key/ value pairs.
To restrict it to a specific value only, replace the value part with the specific item:
C#
string input = "{\"Id\":null,\"FName\":\"Vicky\",\"LName\":\"Denny\",\"DateofJoining\":null,\"Date\":\"2023 - 08 - 01T00: 00:00\",\"CreatedBy\":\"ICC0000389\"}";
string searchFor = "Vicky";
string regex = $"(?<Key>\".*?\":)\"(?<Value>{searchFor})\"";
if (Regex.IsMatch(input, regex))
    {
    Console.WriteLine("Matched");
    }
else
    {
    Console.WriteLine("Not Matched");
    }
}
 
Share this answer
 
Comments
PIEBALDconsult 9-Aug-23 16:48pm    
Hmmm... as long as inserting the searchFor value doesn't produce an invalid RegEx.
Your question is a bit vague and should be improved.
Here's another RegEx-based technique, but I don't recommend it as a general solution.

C#
string sought = "join";
string jsondata = @"{""Id"":null,""FName"":""Vicky"",""LName"":""Denny"",""DateofJoining"":null,""Date"":""2023 - 08 - 01T00: 00:00"",""CreatedBy"":""ICC0000389""}" ;

System.Text.RegularExpressions.MatchCollection mat = System.Text.RegularExpressions.Regex.Matches
(
  jsondata
,
  @"(^|\G)(\s|,|\{|\}|\[|\])*((""(?'Name'[^""]+)""\s*:\s*)?((""(?'Value'[^""]*?)"")|(?'Value'\w+)))"
) ;

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

  if ( val.Success && val.Value.ToLower().Contains ( sought ) )
  {
    // value contains sought text
  }
}
 
Share this answer
 

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