Part of String Case Insensitive in JavaScript Regex (?i) option not working

笑着哭i 提交于 2019-12-02 04:01:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!