Using Regular Expressions (Regex) in X++ for Data Validation and Extraction

 

🔍 Using Regular Expressions (Regex) in X++ for Data Validation and Extraction

When working with Microsoft Dynamics 365 Finance and Operations (D365FO), you may encounter scenarios where you need to validate input data, extract patterns from strings, or ensure a field follows a specific format. That’s where Regular Expressions (Regex) come into play.

In this blog post, we’ll explore how to use Regex in X++, leveraging .NET interop with System.Text.RegularExpressions.


🧠 What is Regex?

Regular Expressions are patterns used to match character combinations in strings. In X++, you can utilize the full power of .NET's System.Text.RegularExpressions.Regex class to implement Regex functionality.


✅ Getting Started: Simple Match Example

Here's how you can check if a string contains numbers:

using System.Text.RegularExpressions; public static void matchRegexExample(Args _args) { str input = "abc123"; str pattern = @"\d+"; // Matches one or more digits Regex regex = new Regex(pattern); Match match = regex.Match(input); if (match.Success) { info(strFmt("Match found: %1", match.Value)); } else { warning("No match found."); } }

✅ Validating an Email Address

This method checks whether a given email address is valid using a basic Regex pattern.


public static boolean isValidEmail(str email) { str pattern = @"^[\w\.-]+@[\w\.-]+\.\w{2,4}$"; Regex regex = new Regex(pattern); return regex.IsMatch(email); }

✅ Extracting Numbers from a String

Want to grab all numbers from a given string? Here's how:


public static void extractNumbers(Args _args) { str input = "Order123 and PO456"; str pattern = @"\d+"; Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(input); int i; for (i = 0; i < matches.get_Count(); i++) { Match match = matches.get_Item(i); info(strFmt("Number found: %1", match.Value)); } }

📘 Common Regex Patterns

PatternMeaning
\dDigit (0–9)
\wWord character (letters, digits, _)
\sWhitespace
.Any character except newline
^ and $Start and end of string
*, +, ?Quantifiers (0+, 1+, 0–1)
[a-z]Character range

⚠️ Things to Keep in Mind

  • Always use using System.Text.RegularExpressions; at the top of your X++ class or method.

  • Make sure your pattern strings are properly escaped if needed.

  • You can use Regex.Match, Regex.IsMatch, and Regex.Matches as needed.


🎯 Final Thoughts

Regular Expressions are a powerful tool for data validation and pattern extraction in D365FO. Using .NET’s Regex class within X++ allows you to implement dynamic checks and parsing logic cleanly without writing lengthy string manipulation code.

Whether you're validating email addresses, invoice numbers, or extracting data from user input — Regex makes your code cleaner, smarter, and more efficient.

Comments