Tag Archives: .NET

Stripping String to Alphanumeric in Microsoft Dynamics Nav using Regex

Within Microsoft Dynamics NAV, there are a few times which an input string needs stripping back to alphanumeric characters.

For example:

  • Unique Identifiers
  • Shipping Tracking Numbers
  • Vehicle Registration Numbers
  • etc

This can be done directly in C/AL, or also using .NET.

Strip String to AlphaNumeric CALDirectly in C/AL:
Directly in CAL, you need to create a function as follows:
Name: StrinStringToAlphaNum
Accepts: Text - 250
Returns Text - 250
Local Variables:

  • tempString - Text
  • i - Integer


The code required is:

 IF STRLEN(StringToStrip)=0 THEN
   EXIT(StringToStrip);

 FOR i:= 1 TO STRLEN(StringToStrip) DO
   BEGIN
    IF StringToStrip[i]IN ['a'..'z','A'..'Z','0'..'9'] THEN
      BEGIN
          tempString:=tempString+FORMAT(StringToStrip[i]);
      END;
   END;
  EXIT(tempString);

Strip String to AlphaNumeric DOTNETUsing .NET:
Directly in .NET needs less code, but is only suitable for Nav 2009 onwards (NAV 2009, 2009 R2, 2013, 2013 R2 and 2015).

Local Variables:

  • RegEx - DotNet - System.Text.RegularExpressions.Regex.'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

The code required is:

"Output String" := RegEx.Replace("Input String",'[^A-Za-z0-9]','');

Comparison
The Regex method is less code, but only works on newer versions of NAV. Whereas the C/AL only method works on older versions. (If you use the “classic client”, it’s an old version and doesn’t support .NET)

I’ve not tested both methods for speed, but both are really quick and not noticeable to the user.

Regex could be used for other things too, such as providing validation, classic examples being:

  • E-Mail Address
  • Phone Numbers
  • Website Addresses
  • etc

The Regular Expression Library is a good starting point for these regular expressions.

Maybe at some point I’ll provide some details on how to do these.