使用javascript在Datatable搜索功能中匹配逗号分隔字符串的正则表达式

使用javascript在Datatable搜索功能中匹配逗号分隔字符串的正则表达式,javascript,jquery,regex,datatable,Javascript,Jquery,Regex,Datatable,我有一个字符串作为 str="NA,No Therapis delivered,No Therapies Available,None,ATP,CVRT,CVRT x 2,No VT Available,Aborted CVRT,Aborted Defib,Defib,Defib(DBT)" 我想要一个匹配逗号分隔值的正则表达式。 我使用Datatable在表中显示上述字符串。 e、 g如果我输入'cvrt',则只应返回上述strin中的'cvrt'。 如果我输入'No Therapis de

我有一个字符串作为

str="NA,No Therapis delivered,No Therapies Available,None,ATP,CVRT,CVRT x 2,No VT Available,Aborted CVRT,Aborted Defib,Defib,Defib(DBT)"
我想要一个匹配逗号分隔值的正则表达式。 我使用Datatable在表中显示上述字符串。 e、 g如果我输入'cvrt',则只应返回上述strin中的'cvrt'。 如果我输入'No Therapis delivered',则只应返回'No Therapis delivered'

由于我想进行数据表搜索,split方法对我来说不起作用。 唯一的选择是使用正则表达式


提前感谢

您可以尝试这样的方法:^ |,没有可用的治疗,|$。这将查找一个特定的单词,在这种情况下,不可用的单词前面有字符串^的开头或逗号,后面是另一个逗号或字符串$的结尾

根据前面的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);
}
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);
编辑2:

逗号将是匹配的一部分,因为它们是模式的一部分。我的最新答案是使用小组来解决这个问题,这似乎不是你能接触到的东西。要解决这个问题,您可以这样做:

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

这是我所需要的,但是使用/^ |,没有可用的治疗,|$/这个RegExp,它也会返回逗号,没有可用的治疗方法”。我不希望逗号被返回。我们能稍微修改一下上面的Reg Exp以从结果中排除逗号吗?谢谢你的回答。当我使用DataTableFilterAPI进行搜索时,以上内容由datatable本身负责。我想做的事情如下:$'example'.dataTable.fnFilter^ |,+searchText+,|$/g,columnIndex,true;但是^ |,+searchText+,|$返回我,searchText,我不希望在结果集中返回逗号。我们可以修改正则表达式位吗??感谢在数据表筛选中,我们将无法对匹配的字符串进行任何后期处理。这就是我想要一个不带前导和尾随逗号的完整正则表达式的原因。@user3534391:那么剩下的唯一选择就是传递您要查找的字符串。问题是它也将匹配子字符串,因此搜索foo将匹配foo,这是foo abc。@在您的第二次编辑中添加注释//删除尾随逗号的npinti。你不应该用$而不是,^吗?