Can we ignore case when doing ballerina regexp matches

103 Views Asked by At

I am trying to match regardless of case.

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

Should match both Axis or axis.

2

There are 2 best solutions below

0
Tim M. On BEST ANSWER

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
0
Sasindu Dilshara On

You can use following code snippet to achieve your task in Ballerina

import ballerina/io;
import ballerina/lang.regexp;

string str1 = "Axis";
string str2 = "axis";
string str3 = "aXIs";
string str4 = "aXIss";

public function main() {
    regexp:RegExp pattern = re `(?i:(ax|test)is$)`;
    io:println(pattern.isFullMatch(str1)); // true
    io:println(pattern.isFullMatch(str2)); // true
    io:println(pattern.isFullMatch(str3)); // true
    io:println(pattern.isFullMatch(str4)); // false
}

Ballerina uses non-capturing groups to control the behavior of regular expression patterns.

So the above regex pattern contains a non-capturing group pattern and it have i flag inside the parentheses.

This i flag makes the pattern case-insensitive. (?i:<pattern>) means that, the pattern will match without considering the case of the pattern.

You can find more details about non-capturing groups and flags of Ballerina in here.