Alex Chard
Alex Chard

Reputation: 41

Java Check string has only certain words and characters

I'm trying to verify that a String only contains certain words and characters.

I'm going to receive a string, and need to check that it only contains the following:

If there is any other character or word in the string, I need to reject it.

A valid string would be: (1 OR ((2 AND 3) OR 4 AND 5))

I think a regex is the way to be going about this, but I can't work out how to build the regex to do this.

I know the regex patterns are:

I've joined them together, so the pattern is: "\sOR\s|\sAND\s|\d+|\(|\)"

This obviously works in that it will find any of the values, but won't reject the string if there are extra characters or strings in the string.

I don't have to use a regex, but as I'm learning about them, this would be an ideal example for some help. I've been using http://www.regexplanet.com/advanced/java/index.html to test different combinations, but have admitted defeat for now.

Any help appreciated.

Upvotes: 0

Views: 1539

Answers (2)

Keppil
Keppil

Reputation: 46219

You can use your constructed regex together with the matches() method provided you escape all your \ and allow repeated occurences with the + operator:

boolean happy = testString.matches("(\\sOR\\s|\\sAND\\s|\\d+|\\(|\\))+");

I'm not sure what you mean by less than 10, but if you mean that the number can be 0-9, you can just replace \\d+ with \\b\\d\\b. If instead you mean 1-9 digits are allowed, you can use \\b\\d{1,9}\\b.

Upvotes: 2

Thom
Thom

Reputation: 15052

I would take your acceptable characters and place them in a constant. Then take the String your testing and turn it into a character array and go through it character by character and see if it is in your constant. Blow up if not. Successful completion = good String.

I don't think there's a shorter way.

Upvotes: 0

Related Questions