问题
Oki before you all admins start marking this question duplicate referencing this SO question How to make regex case-insensitive? I want to clarify that the other referenced question doesn't answer my problem.
I am using Nodejs to build application in which I need to process certain strings I have used the JS "RegExp" object for this purpose. I want only a part of my string in the regex to be case insensitive here's my code
var key = '(?i)c(?-i)ustomParam';
var find = '\{(\\b' + key +'\\b:?.*?)\}';
var regex = new RegExp(find,"g");
But it breaks with following error
SyntaxError: Invalid regular expression: /{(\b(?i)c(?-i)ustomParam\b:?.*?)}/
I will get the key from some external source like redis and the string to be matched from some other external source , I want that the first alphabet should be case-Insensitive and the rest of alphabets to be case-Sensitive.
When I get the key from external source I will append the (?i) before the first alphabet and (?-i) after the first alphabet.
I even tried this just for starters sake, but that also didn't work
var key ='customParam';
var find = '(?i)\{(\\b' + key +'\\b:?.*?)\}(?-i)';
var regex = new RegExp(find,"g");
I know I can use "i" flags instead of above ,but that's not my use case. I did it just to check.
回答1:
JavaScript built-in RegExp
does not support inline modifiers, like (?im)
, let alone inline modifier groups that can be placed anywhere inside the pattern (like (?i:....)
).
Even XRegExp cannot offer this functionality, you can only use (?i)
on the whole pattern declaring it at the pattern beginning.
In XRegExp, you can define the regex ONLY as
var regex = XRegExp('(?i)\\{(\\b' + key +'\\b:?.*?)\\}', 'g');
来源:https://stackoverflow.com/questions/37207947/part-of-string-case-insensitive-in-javascript-regex-i-option-not-working