如何为用户实现正则表达式

时间:2014-01-13 17:03:38

标签: regex code-snippets

我有一个基于用户输入的输入字段和过滤器,然后可以找到具有特定值的所有表格单元格。示例:“50”将隐藏除表格单元格不等于50的行之外的所有行。

片段:

var searchVal = $('#search').val();
$('tbody tr').each(function(index, row) {
   var myText = $(row).children('td:eq(3)').text();
   if (myText != searchVal) {
      $(row).hide();
   }
});

问:我如何在搜索中添加模式匹配或正则表达式?例如,我想让我的用户能够输入“> 50”来查找值大于50的所有表格单元格。

2 个答案:

答案 0 :(得分:2)

我会尝试这样的事情:

var searchVal = $.trim($('#search').val());
var res = searchVal.match(/^[<>]?\d+$/);
if (res !== null) {
        var myText = $(row).children('td:eq(3)').text();
        if (res[0].charAt(0) === '<') {
            if (res[0].substr(1) < myText) {
                // handle case for less than #
            }
        } else if (res[0].charAt(0) === '>') {
            if (res[0].substr(1) > myText) {
                // handle case for greater than #
            }
        } else if (myText === res[0]) {
            // handle case for equal to # (ie. no symbol given in string)
        } else {
            // handle case for not equal to # (ie. no symbol given in string)
            $(row).hide();
        }
} else {
    // handle case where user input does not match
}

答案 1 :(得分:1)

>50不是正则表达式。您需要将数值与数学运算符进行比较,尽管您可以使用类似这样的正则表达式来测试这种可能性:

//if searchVal matches greater/less than and at least one number:
var searchVal = $('#search').val();
var matches = searchVal.match(/^([<>])(\d+)$/);
if (matches[1] == "<") {
    $('tbody tr').each(function(index, row) {
        var myText = $(row).children('td:eq(3)').text();
        if (myText >= parseInt(matches[2]))
           $(row).hide();
    });
}
else if (matches[1] == ">") {
    $('tbody tr').each(function(index, row) {
        var myText = $(row).children('td:eq(3)').text();
        if (myText <= parseInt(matches[2]))
           $(row).hide();
    });
}

但是,如果你想要使用实际的正则表达式,你可以使用Javascript的RegExp.prototype.test()

var searchVal = $('#search').val();
var re = new RegExp(searchVal);
$('tbody tr').each(function(index, row) {
   var myText = $(row).children('td:eq(3)').text();
   if (re.test(myText)) {
      $(row).hide();
   }
});