0

使用 javascript 正则表达式,你如何匹配一个字符而忽略任何其他也匹配的字符?

示例 1:我想匹配 $,但不是 $$ 或 $$$。示例 2:我想匹配 $$,但不匹配 $$$。

正在测试的典型字符串是“$ $$ $$$ asian italian”

从用户体验的角度来看,用户选择或取消选择其值与项目列表中的标签匹配的复选框。必须匹配(检查)所有标签才能显示项目。

    function filterResults(){

// Make an array of the checked inputs
var aInputs = $('.listings-inputs input:checked').toArray();
// alert(aInputs);
// Turn that array into a new array made from each items value.
var aValues = $.map(aInputs, function(i){
    // alert($(i).val());
    return $(i).val();
});
// alert(aValues);
// Create new variable, set the value to the joined array set to lower case.
// Use this variable as the string to test
var sValues = aValues.join(' ').toLowerCase();
// alert(sValues);

// sValues = sValues.replace(/\$/ig,'\\$');
// alert(sValues);

// this examines each the '.tags' of each item
$('.listings .tags').each(function(){
    var sTags = $(this).text();
    // alert(sTags);
    sSplitTags = sTags.split(' \267 '); // JavaScript uses octal encoding for special characters
    // alert(sSplitTags);
    // sSplitTags = sTags.split(' \u00B7 '); // This also works

    var show = true;

    $.each(sSplitTags, function(i,tag){

        if(tag.charAt(0) == '$'){
            // alert(tag);
            // alert('It begins with a $');
            // You have to escape special characters for the RegEx
            tag = tag.replace(/\$/ig,'\\$');
            // alert(tag);
        }           

        tag = '\\b' + tag + '\\b';

        var re = new RegExp(tag,'i');

        if(!(re.test(sValues))){
            alert(tag);
            show = false;
            alert('no match');
            return false;
        }
        else{
            alert(tag);
            show = true;
            alert('match');
        }
    });

    if(show == false){
        $(this).parent().hide();
    }
    else{
        $(this).parent().show();
    }

});

// call the swizzleRows function in the listings.js
swizzleList();
}

提前致谢!

4

3 回答 3

2

通常,使用正则表达式,您可以使用(?<!x)x(?!x)来匹配一个 x既不在前面也不在后面的x

借助现代 ECMAScript 2018+ 兼容的 JS 引擎,您可以使用基于后视的正则表达式:

(?<!\$)\$(?!\$)

查看 JS 演示(仅在支持的浏览器中运行,它们的数量正在增长,请查看此处的列表):

const str ="$ $$ $$$ asian italian";
const regex = /(?<!\$)\$(?!\$)/g;
console.log( str.match(regex).length ); // Count the single $ occurrences
console.log( str.replace(regex, '<span>$&</span>') ); // Enclose single $ occurrences with tags
console.log( str.split(regex) ); // Split with single $ occurrences

于 2020-05-26T10:27:09.933 回答
1
\bx\b

说明:在两个单词边界之间匹配 x(有关单词边界的更多信息,请查看本教程)。\b包括字符串的开头或结尾。

我正在利用您问题中的空格分隔。如果那不存在,那么您将需要一个更复杂的表达式,例如(^x$|^x[^x]|[^x]x[^x]|[^x]x$)匹配可能在字符串开头和/或结尾的不同位置。这会将其限制为单个字符匹配,而第一个模式匹配整个标记。

另一种方法是对字符串进行标记(将其拆分为空格)并从标记构造一个对象,您可以查看它以查看给定字符串是否与其中一个标记匹配。这应该比正则表达式的每次查找要快得多。

于 2012-10-09T20:48:52.763 回答
0

像这样的东西:

q=re.match(r"""(x{2})($|[^x])""", 'xx')

q.groups() ('xx', '')

q=re.match(r"""(x{2})($|[^x])""", 'xxx')

q is None True
于 2012-09-28T21:38:21.500 回答