Regular Expressions
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 the Resources in your solution and set the path to /script_lib
.
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
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:
groovy
1RegAnnotHelper.annotateAnchored(_, /(?<swedishZipCode>\d{3}\s?\d{2})/)
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:
groovy
1RegAnnotHelper.annotateAnchoredRegex(_, 'SWEDISH_ZIP_CODE', /\d{3}\s?\d{2}/)
2
which does the same, but with the name specified as a parameter instead of the named capture group.
Matching on multiple groups
groovy
1RegAnnotHelper.annotateAnchored(_, /(?<amount>\d+(?:\.\d+)?)(?<unit>[a-zA-Z]+)/)
2
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:
lml
1%$AMOUNT^{amount=lob.value}&=%$UNIT^{unit=lob.value}
2