简体   繁体   English

正则表达式匹配整个字符串,但不区分大小写

[英]Regular expression to match whole string but case insentitive

I have a list of codes that I loop through, and for each code I need to check for an exact but non-case sensitive match when a form is submitted. 我有一个循环的代码列表,提交表单时,我需要为每个代码检查一个精确但不区分大小写的匹配项。

I hva come up with a solution using a regular expression, but it's not quite perfect (it ignores case, but it will return partial matches). 我用正则表达式提出了一个解决方案,但是它不是很完美(它忽略大小写,但是会返回部分匹配项)。

For example, take this sample from my list of codes - 例如,从我的代码列表中获取此示例-

EXC EXC
EXD EXD
EXD1 EXD1

If ex is submitted no matches should be found (but all 3 examples are matched), and if exd is submitted only EXD should be matched (but EXD1 is also matched). 如果ex提交不匹配应该找到(但所有3个实例匹配),如果exd被提交仅EXD应匹配(但EXD1也匹配)。

In the code below val is the user input from the form and v.code is each looped code - val下面的代码中,是表单中的用户输入,而v.code是每个循环的代码-

if(v.code.search(new RegExp(val, "i")) >= 0){ ...

How can I amend this code to meet my requirements? 如何修改此代码以满足我的要求? Thanks. 谢谢。

Build the regular expression with start and end anchors: 使用开始和结束锚点构建正则表达式:

if (new RegExp("^" + val + "$", "i").test(v.code)) {
  // match!
}

If you're worried about performance should there be a whole lot of codes to test, you could pre-construct the regular expressions so that you don't have to do so for each validation. 如果您担心性能是否需要测试大量代码,则可以预先构造正则表达式,这样就不必为每次验证都这样做。

You could do this without regex at all by: 您可以完全不用正则表达式来执行此操作:

if (val.toLowerCase() == "insensitive string".toLowerCase())
{
    // ...
}

使用单词边界:

new RegExp('\\b'+val+'\\b', "i")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM