javascriptregexdelphismart-mobile-studio

Regular expressions in Smart Mobile Studio


How do I work with regular expressions in Smart Mobile Studio? For example, how do I code following example in Object Pascal?

var re = /\w+\s/g;  
var str = "fee fi fo fum";  
var myArray = str.match(re);  
console.log(myArray);

Solution

  • In SmartMS, regular expressions are implemented in the w3regex unit so you start by adding w3regex to the uses list.

    'Short' form (such as var re = /\w+\s/g; from the question) is not supported. To create a regular expression object, you have to use a constructor.

    re := TW3RegEx.Create('\w+\s', 'g');
    

    Built-in string object does not support regex matching. To simplify usage, the w3regex unit implements string helpers which introduce Match, Replace, Search and Split methods to the string object.

    A direct translation of your code would be

    var re := TW3Regex.Create('\w+\s', 'g');
    var str := 'fee fi fo fum';
    var myArray := str.Match(re);
    

    (As for logging, I don't know at the moment how to nicely write a string array to a console but that was not part of the question.)

    w3regex implements few overloads for the Match method which will create regex object on the fly for you. As you can also apply helper methods to a string literal, you can shorten the code to:

    var myArray: TStrArray = ('fee fi fo fum').Match('\w+\s', 'g');
    

    Parenthesis around the string literal are required in this case.

    Many ways of using the regex in SmartMS are documented in the RegExDemo program which is part of the installation.