How to test simple regex's

The program we use to test regular expressions is written in a language called Groovy. It is therefore useful to test your regular expressions using a Groovy interpreter, so that you know you are getting the same results we get when we grade homework. Groovy uses Java libraries under the hood, so if you know Java, you can test your regex's in that language as well. However, if you don't know either language, the instructions below are the simplest way to test your regex's.

Go to this website, where you can type arbitrary Groovy code to be executed. Most people don't know Groovy, but the following example code is all you should need. It is easily modified to test your solutions to regex homework problems. (Unfortunately if you copy and paste, it may remove the newlines, so you'll have to re-insert them yourself.)

          regex = /0|((1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)*)/

          println "12092" ==~ regex
          println "092" ==~ regex
          println "12a092" ==~ regex
          println "0" ==~ regex

Type that code into the console and then click "Execute script". You should see the following appear under "Output":


In the first line of code, the pair of characters / at the start and end signify a regular expression. (regex actually just points to an object of type String, but using /.../, rather than "..." as Strings are normally specified, makes it easier to type the regex since fewer escape sequences are necessary using the former notation.) Therefore the regular expression itself is what lies in between them:


The println statements print the Boolean result of testing various strings against the regular expression. The strings "12092" and "0" match the regular expression, but "092" and "12a092" do not.

One word of warning: like most regex libraries, Groovy's can do a lot more sophisticated expressions than just those using (, ), |, *, and symbols from the input alphabet. However, for homework purposes, you can only use these symbols (and not, for example, \d to represent (0|1|2|3|4|5|6|7|8|9), even though Groovy will allow this).