You can test whether text matches a regular-expression pattern in an OCL expression by using regExpMatch; use it when a property must conform to a defined text format.
Match text with regExpMatch
regExpMatch is an OCL operator that evaluates a string against a regular expression and returns a Boolean result:
truewhen the string matches the pattern.falsewhen the string does not match the pattern.
Write the string first, followed by .regExpMatch(...). Both the value and the pattern are written as quoted strings in this example.
'åke.öberg@mdriven.se'.regExpMatch('^[a-öA-Ö0-9+_.-]+@[a-öA-Ö0-9.-]+\.[a-zA-Z]{2,3}$')
This expression returns true.
Example: test an email-shaped value
The following pattern tests whether the complete value has the structure used in the example: text before @, text after @, a dot, and a final segment of two or three letters.
'åke.öberg@mdriven.se'.regExpMatch('^[a-öA-Ö0-9+_.-]+@[a-öA-Ö0-9.-]+\.[a-zA-Z]{2,3}$')
| Pattern part | Meaning in this example |
|---|---|
^
|
Starts the match at the beginning of the value. |
[a-öA-Ö0-9+_.-]+
|
Requires one or more of the listed letters, digits, or symbols before @.
|
@
|
Requires the at-sign separator. |
[a-öA-Ö0-9.-]+
|
Requires one or more of the listed characters after @ and before the final dot.
|
\.
|
Requires a dot. |
[a-zA-Z]{2,3}
|
Requires a final segment containing two or three English letters. |
$
|
Ends the match at the end of the value. |
Because the pattern begins with ^ and ends with $, it tests the entire string rather than only part of it. For example, the pattern is intended to reject a value with extra text before or after the email-shaped value.
Use the result in an OCL condition
Since regExpMatch returns a Boolean value, you can use it wherever an OCL condition is required. For example, if Email is a string-valued property in the current context:
self.Email.regExpMatch('^[a-öA-Ö0-9+_.-]+@[a-öA-Ö0-9.-]+\.[a-zA-Z]{2,3}$')
Keep the pattern aligned with the format that your model requires. The example pattern is specific: it allows the listed characters and requires a two- or three-letter final segment. Change the pattern when your accepted format has different rules.
