You can override the ‘i’, ‘m’, and ‘s’ flags for a local part of a regular expression. They are called modifiers. A modifier can either enable or disable the above mentioned flags. The syntax for the modifers if of the form(?flags1:pattern)(?flags1-flags2:pattern)
Both flags1 and flags2 are optional, but at least one of them should be present. The modifer flags and the pattern should be in parentheses and the applicability of the modifiers is only within those parentheses. (?flags1-:pattern) is a modifier that only enables flags (equivalent to (?flags1:pattern)). (?-flags2:pattern) is a modifier that only disables flags. Other flags like ‘d’, ‘y’, ‘g’, ‘u’ and ‘v’ doesn’t make sense in a modifier.
If you want to match patterns of the form ‘lastName, firstName\n’, where lastName can be in any case, you can apply a localized ‘i’ flag using modifiers like/(?i:[a-zA-Z]+), [A-Z][a-z]*(?=$|\s+)/g
The modifier states that the last name part can be in any case
let wordPttn = /(?i:[a-zA-Z]+), [A-Z][a-z]*(?=$|\s+)/g; let targetString = `DOE, JohnDoe, JohndOE, JohnDoe, JOhnBill, KillBILL, Kill`let results = targetString.matchAll(wordPttn);for (let result of results) { console.log(result[0]);}
Output:
DOE, John
Doe, John
dOE, John
Bill, Kill
BILL, Kill
The above pattern could also be written as/[a-zA-Z]+, (?-i:[A-Z][a-z]*)(?=$|\s+)/ig
Here we are apply the 'i' flag to the whole regular expression and then remove it for the first name portion with (?-i:)
let wordPttn = /[a-zA-Z]+, (?-i:[A-Z][a-z]*)(?=$|\s+)/ig; let targetString = `DOE, JohnDoe, JohndOE, JohnDoe, JOhnBill, KillBILL, Kill`let results = targetString.matchAll(wordPttn);for (let result of results) { console.log(result[0]);}
Output:
DOE, John
Doe, John
dOE, John
Bill, Kill
BILL, Kill