Daemon
Daemon

Reputation: 185

String comparison in Java without spaces

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 :-

  1. ansDt : [* TO *]
  2. ansDt : [someDate TO *]
  3. ansDt : [* TO someDate]
  4. ansDt : [someDate TO otherDate]

I have two doubts:-

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

Answers (4)

ericccs
ericccs

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

basiljames
basiljames

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

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

This should do (for strings s1 and s2):

s1.replace(" ", "").equals(s2.replace(" "), ""))

Upvotes: 0

duffymo
duffymo

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

Related Questions