0

Need to write a quick method static boolean varTest(String id) that tests of the input is indeed a variable based on the following rules:

variable ::= a dollar sign ($) followed by an integer, or any identifier starting with a letter followed by a mix of letters or digits.

Where for example both x$ or $x can be var's without this test.

So if not true, I want to throw ArithmeticException

1 Answer 1

3

You're looking for a regular expression: $(\$[0-9]+)|([a-zA-Z][a-zA-Z0-9]*)^.

For example:

static Pattern p = Pattern.compile("$(\\$[0-9]+)|([a-zA-Z][a-zA-Z0-9]*)^");
static boolean varTest(String id) {
    return p.matcher(id).matches();
}
Sign up to request clarification or add additional context in comments.

2 Comments

.matches returns true/false I assume?
@John: Yes; it returns a boolean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.