Reputation: 185
Folks,
I am having a little doubt with String comparison (with blank spaces in between) in Java .
UseCase :-
Consider the following Solr query string :-
String query = ".....&ansDt:[* TO *]....";
Valid format for ansDt are :-
ansDt : [* TO *]
ansDt : [someDate TO *]
ansDt : [* TO someDate]
ansDt : [someDate TO otherDate]
I have two doubts:-
Now, I need a way to check the query string for only 4th ansDt
format. If other format is encountered ( in short, if any *
pattern is encountered in ansDt
field) , I need to throw some message on console.
Also I need to check for 1st, 2nd and 3rd case irrespective of blank spaces between ansDt
& :
& [
. i.e ansDt: [* TO *]
, ansDt :[* TO *]
, ansDt : [ * TO *]
etc are all considered same
I cannot use String.trim( )
because it will remove only the leading and ending whitespaces for a string
How do I check that with Java String comparison ?
Thanks
Upvotes: 2
Views: 2421
Reputation: 66
Please try this regex:
String query = ".....&ansDt:[* TO *]....";
String pattern = ".*ansDt[\\ ]*[:][\\ ]*[\\[].*[\\ ]+TO[\\ ]+.*[\\]].*";
boolean test = query.matches(pattern);
Additional info:
. matches any character
.* matches any amount of characters
[\ ] matches space
[\ ]+ matches one or more spaces, used between "TO"
[\ ]* matches any amount of spaces, used between ":"
[\[] and [\]] matches "[" and "]"
Upvotes: 3
Reputation: 4847
Regex is the way to go. But for a quick fix you can try
String query = ".....&ansDt : [ * TO *]....";
int indexOfansDt = query.indexOf("ansDt");
int indexOfBeginBracket = query.indexOf("[",indexOfansDt);
int indexOfEndBracket = query.indexOf("]",indexOfBeginBracket);
String yourString = query.substring(indexOfBeginBracket, indexOfEndBracket+1);
System.out.println(yourString);
Check yourString
for indexOf("*")
, if it is not -1
your format is 1,2 or 3. But there are a lot of error cases, NPEs that you have to check for.
Upvotes: 1
Reputation: 7197
This should do (for strings s1
and s2
):
s1.replace(" ", "").equals(s2.replace(" "), ""))
Upvotes: 0
Reputation: 308763
You'll need something more complex than a simple regex. You've written what amounts to a four line grammar. You should take the approach that a parser generator would: tokenize it and then execute rules to see if the tokens match your grammar.
If you can stand the big hammer of a parser generator, I'd recommend ANTLR.
Upvotes: 0