Regex Annotator

The Regular Expression Annotator is a groovy helper class which serves as adapter between regular expressions and annotations.

The parts of the user's input that match the regular expression will be annotated, making it possible to use the annotations in language conditions.

Installation

Add the file RegAnnotHelper.groovy to Resources in your solution and set the path to /script_lib.

For more details on managing files in your solution, see Resource File Manager.

Usage

Create a Global, pre-listener to handle annotations. Ideally, all the RegAnnotHelper calls should be placed in the same listener, using a * condition and have and stop testing... set to After All tested.

Example of listener configuration

Example

Swedish zip codes have the format of 3 digits followed by whitespace followed by 2 digits. If we would like to have those annotated, we should proceed as follows:

Add the call in the RegAnnotHelper listener with the script:

RegAnnotHelper.annotateAnchored(_, /(?<swedishZipCode>\d{3}\s?\d{2})/)

This will annotate matching zip codes with the name SWEDISH_ZIP_CODE. It will also add an annotation variable 'value' with the matched value.

Alternatively you can use:

RegAnnotHelper.annotateAnchoredRegex(_, 'SWEDISH_ZIP_CODE', /\d{3}\s?\d{2}/)

which does the same, but with the name specified as a parameter instead of the named capture group.

Matching on multiple groups

RegAnnotHelper.annotateAnchored(_, /(?<amount>\d+(?:\.\d+)?)(?<unit>[a-zA-Z]+)/)

The expression above adds two annotations to a pattern like '100m':

  • %$AMOUNT
    will have an annotation variable 'value' with value '100'
  • %$UNIT
    will have an annotation variable 'value' with value 'm'.

In a language condition you can then get the number and the unit as follows:

%$AMOUNT^{amount=lob.value}&=%$UNIT^{unit=lob.value}

Was this page helpful?