JavaScript Regex(?i)选项不敏感的字符串大小写部分不起作用 [英] Part of String Case Insensitive in JavaScript Regex (?i) option not working

查看:119
本文介绍了JavaScript Regex(?i)选项不敏感的字符串大小写部分不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在你们所有管理员开始标记这个问题之前,Oki引用这个问题重复如何制作正则表达式不区分大小写?
我想澄清其他引用的问题不能解决我的问题。



我正在使用Nodejs来构建我需要处理某些字符串的应用程序我为此使用了JSRegExp对象。
我只希望正则表达式中我的一部分字符串不区分大小写
这里是我的代码

  var key ='(?i)c(? -  i)ustomParam'; 
var find ='\ {(\\b'+ key +'\\b:?。*?)\}';
var regex = new RegExp(find,g);

但它会因以下错误而中断

  SyntaxError:无效的正则表达式:/ {(\ b(?i)c(? -  i)asomParam \b:?。*?}} / 

我将从一些外部源获取密钥,如redis和要从其他外部源匹配的字符串,我想要第一个字母表应该是不区分大小写的,其余字母表区分大小写。



当我从外部源获取密钥时,我会在(?i)之前附加(?i)第一个字母和第一个字母后的(?-i)。



我甚至尝试过这只是为了初学者的缘故,但这也没有用

  var key ='customParam'; 
var find ='(?i)\ {(\\b'+ key +'\\b:?。*?)\}(? - i)';
var regex = new RegExp(find,g);

我知道我可以使用i标志代替上面的标志,但这不是我的用例。我这样做是为了检查。

解决方案

JavaScript内置 RegExp 不支持内联修饰符,例如(?im),更不用说内联修饰符组可以放在任何地方里面模式(如(?i:....))。



甚至 XRegExp无法提供此功能,您只能在整体上使用(?i)模式在模式开始时声明它。



在XRegExp中,您只能将正则表达式定义为

  var regex = XRegExp('(?i)\\ {(\\ b'+ key +'\\b:?。*?)\\}','g'); 


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.

解决方案

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');

这篇关于JavaScript Regex(?i)选项不敏感的字符串大小写部分不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆