简体   繁体   English

正则表达式匹配无故返回null

[英]Regex match returns null for no reason

i am making a client for my node.js irc bot and want to implement tab complete but the regex in the following code returns null for no reason. 我正在为我的node.js irc bot制作客户端,并想实现tab完整,但以下代码中的正则表达式无缘无故地返回null。 i have included what's logged as comments next to the console.log statement. 我在console.log语句旁边添加了记录为注释的内容。

what is tab complete: i type "mic" and press tab, it the automatically completes it to "michael" because he is a user in the channel. 选项卡完成了什么:我键入“ mic”并按tab,它会自动将其完成为“ michael”,因为他是频道中的用户。

tabStart = false;
$("#textbox").keydown(function (e) {
    if (!$(this).val().length) return;
    if (e.keyCode === 9) {
        e.preventDefault();
        var text = $(this).val();
        console.log('text: ' + text);// mic
        var index = text.lastIndexOf(" ");
        console.log('index: ' + index);// -1
        if (!tabStart) {
            tabStart = index > -1 ? text.substr(index + 1) : text;
            var current = '';
        } else {
            var current = index > -1 ? text.substr(index + 1) : text;
        }
        console.log('tabStart: ' + tabStart);// mic
        console.log('current: ' + current);// 
        var active = $("#tabs").tabs("option", "active");
        var channel = $("#tabs ul>li a").eq(active).attr("href");
        console.log('channel: ' + channel);// #debug
        var users = $(channel + " .user-list li");
        var regex = new RegExp("^" + tabStart + ".*", "i");
        console.log('regex: ' + regex);// /^mic.*/i
        for (var i = 0; i < users.length; ++i) {
            var user = $(users[i]).text();
            console.log('user: ' + user);// michael
            var match = user.match(regex);
            console.log('match: ' + match);// null
            if (match) {
                var newText = (index > -1 ? text.substr(0, index + 1) : "") + user;
                console.log('newText: ' + newText);
                $(this).val(newText);
                break;
            }
        }
    } else {
        tabStart = false;
    }
});

as i said, i can't seem to find an explanation for this because i tried the following in the javascript console and it works 如我所说,我似乎找不到对此的解释,因为我在javascript控制台中尝试了以下操作,并且可以正常工作

var regex = new RegExp("^mic.*", "i");"michael".match(regex);

It looks like you have an issue with getting the correct text from users . 您似乎无法从users那里获得正确的文本。 Since I don't know your actual HTML, I created a CodePen and commented out some of the channel lines and added users as a typical array. 由于我不知道您的实际HTML,因此我创建了一个CodePen并注释掉了一些通道行,并将users添加为典型数组。 Doing that, your regex works fine. 这样做,您的regex可以正常工作。

Here is the codePen in action . 这是正在使用的codePen

figured out the problem. 找出问题所在。 user was wrapped in &#8203; user被包裹在&#8203; .

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

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