Verifying that a string is a valid decimal number

I am adding a feature to an existing module to automate combat. That feature prompts the attacker to enter the Attack Factor and Defense Factor of the combat as a string which is expected to be in the format of “AF:DF” where AF and DF are each supposed to be a decimal number between 0 and 99. For example:


The logic in my module currently parses the input string into its two components, separated by the colon character, and verifies that each of those two substrings have a length of 1 or 2. I would like to add error checking to verify that each of those two substrings represent a valid decimal number, by checking that it consists only of the characters “0” through “9”.

I was hoping to find a BeanShell function that could do that, but did not find one in the Vassal reference manual “Expressions” section. I tried to use a regular expression (in the Property Match section of a Trigger trait), but was unsuccessful.

The best method that I can think of to do that syntax checking is to note the starting length of the substring (either 1 or 2), then add 0 to it (substring + 0) and check the length of the resulting value. I’m guessing that BeanShell will try to interpret that substring as a number and if it is, then adding 0 should result in the same number with the same length when treated as a string. This seems very cumbersome however.

Might there be a better way to test whether a string is a valid decimal number?

Jim Hunter.

A Regular Expression would be the usual way to solve this. What did you try that did not work? From memory, Java RE’s (which is what Beanshell implements) are a little quirky.

Perhaps BeanShell


If these are decimal number (can contain a decimal point ‘.’), or


If they are integer (whole numbers).

This does not validate, but gives you zero if the format is invalid. Note the use of GetString rather than GetProperty as the later may return something parse... cannot handle, and thus throw an exception.


1 Like

Thanks to both of you for the ideas and encouragement. I took another try at using RegEx, and got it to work. I think my earlier attempt tried to use the BeanShell “Regular Expression Match” operator (=~) with what I think of as an actual RegEx string, something like this:

Trigger Matching Property: {UserStr =~ “^[0-9]+$”}

The Expressions page in the Reference Guide does not give an example of how to use that operator, but the Regular Expressions section of the Designer Guide shows that what it actually does is provide a compact format to match any one of several strings.

What eventually worked for me was to pass the RegEx string to the Java String method matches(), as shown below:

Thanks again for your help!

Jim Hunter.

FYI, == true is completely redundant.