Reputation: 207
I got a String which can contain:
plain text (a reply for a question or an email for example);
only numbers and "=";
only numbers and "[" "]" ",".
I am trying to find a way to discriminate among those cases and, in particular, to be able to know if that String belongs ONLY to one case (i.e. if it contains plain text and numbers and other characters like "=" or "[" I'd like to put it in the first case, while if it contains ONLY number and "=" I'd like to put it in the second case).
I tried using something like:
if (text.contains("[") && text.contains("]") && text.contains(","))
//other code
but in this case it could be both text and those characters or number and those characters, so I can't decide if I'm in the first or second case.
Thanks for your help.
Upvotes: 3
Views: 5434
Reputation: 11486
This can easily be solved by using regex. Take a look here.
In your case: here are the regexes I would use:
only numbers and "=";
s.matches("[0-9|=]+");
only numbers and "[" "]" ",".
s.matches("[0-9\\[\\],]+");
And the first case is all the rest!
!s.isEmpty();
Upvotes: 4
Reputation: 3841
Go for regex
For numbers:
System.out.println(data.matches("[0-9]+"));
For numbers and '='
System.out.println(data.matches("[0-9=]+"));
For numbers and square brackets and ,
System.out.println(data.matches("[0-9\\[\\],]+") );
For plain text:
System.out.println(data.matches("[a-zA-Z]+"));
where data
is your input text
Upvotes: 3