繁体   English   中英

使用JavaScript在数据表搜索功能中匹配正则表达式以逗号分隔的字符串

[英]Regular Expression to match comma seperated strings in Datatable searching functionality using javascript

我有一个字符串

str="NA,No Therapis delivered,No Therapies Available,None,ATP,CVRT,CVRT x 2,No VT Available,Aborted CVRT,Aborted Defib,Defib,Defib(DBT)"

我想要一个与逗号分隔值匹配的正则表达式。 我正在使用数据表在表中显示以上字符串。 例如,如果我输入“ cvrt”,则仅应返回上述字符串中的“ cvrt”。 如果我输入“未送出任何疗法”,则仅返回“未送出任何疗法”。

当我想进行数据表搜索时,split()方法对我不起作用。 唯一的选择是使用正则表达式。

提前致谢

您可以尝试使用以下方法: (^|,)No Therapies Available(,|$) No Therapies Available的情况下,这将寻找一个特定的单词,该单词以字符串( ^ )的开头或逗号( , )开头,然后以另一个逗号( , )或结尾的逗号结尾。字符串( $ )。

按照这个以前的SO问题,你可以使用exec匹配和获得的搜索结果的位置。

编辑:该代码看起来像这样:

var searchText = ...;
var searchableText = ...;
var match = [];
var regex = "(^|,)(" + searchText + ")(,|$)/g"
while(match = regex.exec(searchableText)) != null)
{
    alert("Item found at " + match[1].index);
}

编辑2:

逗号将是匹配项的一部分,因为它们是模式的一部分。 我更新的答案使用组来解决此问题,看来这不是您可以访问的。 要解决此问题,您可以执行以下操作:

var matchedText =  $('#example').dataTable().fnFilter( "(^|,)" + searchText + "(,|$)/g",columnIndex,true); //this should return a string of the form ',foobar,`
//We then proceed to clean the string by removing leading/trailing commas:
matchedText = matchedText.replace("^,", "");    //Remove leading commas.
matchedText = matchedText.replace(",$", "");    //Remove trailing commas.
alert("Matched Text: " + matchedText);

暂无
暂无

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

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