Monthly Archives: October 2009

Using Regular Expressions in Dynamics AX

When working with strings, ex. replacing text, validating content or simply checking for existence, It can sometimes be a good idea to consider using Regular Expressions (RegExp), insted of using ordinary string manipulation methods.

X++ itself does not seem to support Regular Expressions, but we can use the .NET functionality.

Below is an example method of how to validate that an email address is written in a proper format.

1
2
3
4
5
6
7
8
9
10
11
Static Server boolean validateEmail(EMail   _eMail)
{
    Str MatchEmailPattern =
    @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
    System.Text.RegularExpressions.Match myMatch;
    ;
 
    myMatch = System.Text.RegularExpressions.Regex::Match(
    _eMail, MatchEmailPattern);
    return(myMatch.get_Success());
}

It simply returns true if the input is a properly formatted email.

To replace text in a string you could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static void Job1(Args _args)
{
    Str EmailPattern =
    @"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b";
    Str ReplacedText;
    ;
 
    ReplacedText =
    System.Text.RegularExpressions.Regex::Replace(
    "My email address is: example@haxx.net",
    MatchEmailPattern,"blabla@haxx.net");
 
    print ReplacedText;
    pause;
 
}

This will replace ALL found email addresses.

Below is an example of how to “find” all matches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static void Job6(Args _args)
{
    Str MatchEmailPattern =
    @"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b";
    System.Text.RegularExpressions.Match myMatch;
    ;
 
    myMatch = System.Text.RegularExpressions.Regex::Match(
    "Your email: youremail@host.net, and my"
    +"email: myemail@anotherhost.com", MatchEmailPattern);
 
    while (myMatch.get_Success())
    {
        print myMatch.get_Value();
        myMatch = myMatch.NextMatch();
    }
 
    pause;
}

Notice the difference between the RegExp pattern in this example and the first example.

The first pattern checks if the input is valid.

And this pattern checks for ALL valid matches.

For more information about regular expressions visit:
www.regular-expressions.info