Reputation: 19622
Below are the sample examples of string. In the below four string example, you will find userId
as a key
always.
{siteRebateSenstvty=0;1,1;2, siteRedemptChg=16;30,77;40, userId=101}
{sgmntId=1, userId=101}
{predictedCatRev=0;101;1,1;201;2, predictedOvrallRev=77;2,0;1,16;3, sitePrftblty=77;2,0;1671679, topByrGms=12345.67, usrCurncy=1, vbsTopByrGmb=167167.67, userId=101}
{zipCode=CA11 9QL, userId=101}
So now in my below method, I am trying to validate str
value with id
, I will be passing string and id to isStringValid method
.
private boolean isStringValid(String str, String id) {
boolean valid = false;
System.out.println(str);
return valid;
}
Problem Statement:-
Now I am trying to match id value
with userId value
in the above JSON String
. Meaning if id value is 101
then in the above JSON String
userId
value should also be 101. If any of them doesn't matches or userId value is not there in the string then set the vaild boolean to false
.
What is the best way to do this problem?
I cannot do it like this-
if(str.contains(id))
because it might be possible 101 is present as some number in any keys.
Upvotes: 0
Views: 119
Reputation: 328735
Assuming that the id (101 in your first example) is always followed by ;
,
or }
, you could use:
String str = "{siteRebateSenstvty=0;1,1;2, siteRedemptChg=16;30,77;40, userId=101}";
String id = "101";
boolean valid = str.matches(".*userId=" + id + "[,;}]+.*");
System.out.println("valid = " + valid);
The [,;}]+
part ensures that the next character is not part of the ID (so that 1015a is not considered a valid userId when you expect 101 for example).
Alternatively and probably more robust, you could use a word boundary:
boolean valid = str.matches(".*userId=" + id + "\\b+.*");
Upvotes: 1