Sunday, April 18, 2010

Using TextBuffer class to decode text

It is sometimes of great benefit to be able to identify certain patterns in a text and be able to extract certain information depending on the patterns found. X++ provides this by the power of the use of regular expressions.

For example, the match function in Dynamics Ax can be used to decide whether an item’s name contains a string that starts with a number followed by a string that contains at least two commas.
This pattern can be formulated as a regular expression in the X++ syntax as “:d+.*, .*, .*”. This patter is used in the example below.
 
match(":d+.*, .*, .*","14\", TV, Fixed stand")

The match function in the previous example returns 1, which means that the pattern was found.

The TextBuffer class is founded on the mechanism of the match function. Basically, the matching is triggered by calling the find method. If the pattern is found, the TextBuffer object stores two values that facilitate access to the matching substring, those being the match position (the beginning of the matching substring) and the match length (the length of the matching substring).

The following code example shows how to use the TextBuffer class to identify the presence of three different patterns with special delimiters in an item’s description, namely:

  • conf|.*|: Substring starting with “conf|” and ending with “|”.
  • col|.*|: Substring starting with “col|” and ending with “|”.
  • size|.*|: Substring starting with “size|” and ending with “|”.
These special delimiters are used in a way to locate the configuration, color and size of an item.

The following three steps describe how this is done:

  1. Call the find method to trigger the matching.
  2. Use the matchPos and matchLen methods to locate the matching substring (if any).
  3. Extract the matching substring.
  4. Display the matching substring.
  5. Replace the matching substring with an empty string to remove it from the original text.
Finally, the remaining string (which is the description of the item) is displayed. Note that the strrtrim function is used to remove any trailing spaces from the description of the item.

 image 

No comments:

Post a Comment