Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Using Regex to define variables with Discord.js?

I was advised to use regex with this discord.js project. It saves two mentions from a message into two variables in the order the two mentions are typed. Discord.js reads mentions in the numeric order of the actual IDs, not the actual typed order, so we have to use regex instead. The command string is: f$command @user1 @user2 So, here's my code:

else if (command === 'command'){
        const regex = /<@!?(d+)>/;
        let match = regex.exec(message);
        while (match){
            const User1 = match[1].id;
            const User2 = match[2].id;
        }

Is this correct, and how do I make it require 2 regex matches?

question from:https://stackoverflow.com/questions/65891108/using-regex-to-define-variables-with-discord-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
else if (command === 'command') {
    const regex = /<@!?(d+)>/;
    let match = regex.exec(message);
    const result = [];
    while (match){
        result.push(match[1]);
        match = regex.exec(message);
    }
    if (result.length !== 2) {
        console.error('not 2 matches');
    }
    const User1 = result[0];
    const User2 = result[1];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...