Search code examples
regexballerina

Can we ignore case when doing ballerina regexp matches


I am trying to match regardless of case.

regexp:RegExp pattern = re `(ax|test)is$`;

Should match both Axis or axis.


Solution

  • Use an inline modifier to your regex pattern:

    regexp:regexp pattern = re `(?i:(ax|test)is$)`;
    

    The (?i:...) at the beginning does the trick of turning on case-insensitive mode for the entire pattern. Your code would functions like:

    1. (?i:: Sets case-insensitive matching.
    2. (ax|test): This group matches either "ax" or "test".
    3. is$): Ensures the match ends with the letters "is".

    An example might be:

    import ballerina/io;
    import ballerina/regexp;
    
    public function main() {
        regexp:RegExp pattern = re `(?i:(ax|test)is$)`;
    
        string word1 = "Axis";
        string word2 = "axis";
        string word3 = "TestiS";
    
        if (pattern.isFullMatch(word1)) {
            io:println("Match: " + word1);
        }
    
        if (pattern.isFullMatch(word2)) {
            io:println("Match: " + word2);
        }
    
        if (pattern.isFullMatch(word3)) {
            io:println("Match: " + word3);
        }
    }
    

    This code will output:

    Match: Axis
    Match: axis
    Match: TestiS