首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要Regex帮助:模式几乎有效

需要Regex帮助:模式几乎有效
EN

Stack Overflow用户
提问于 2021-01-18 16:16:14
回答 1查看 44关注 0票数 2

对于ECMAScript的正则表达式,我需要一点帮助。我目前使用的regex几乎可以按需要工作,但是有一个小问题。我需要匹配以下几点:

STATSTATS不管是哪种情况。此外,后面可能还有符号和数字。

示例:stats:3-2是匹配的。stats:5是匹配的。stats-4是一个部分匹配,但是应该忽略'-4‘。

我正在使用的当前正则表达式(如前所述)几乎可以工作,如下所示:/STAT[S]*(?:(?:[\:](?<method>(\d)))(?:[\-](?<count>(\d)+))*)*/ig

此模式使用regex101,实际上匹配所有条件,并在以下示例中忽略-4:stats-4,同时匹配单词'stats‘。

但是,当我试图在我正在编辑的插件中使用此模式时,就会出现问题。它目前只匹配statstatsstat:2,但不匹配stat:3-2stat-4 (应该与'stat‘匹配,但忽略'-4')。

我知道模式可能有点混乱,但我不擅长创建正则表达式。

确切用法(在atom rpg-骰子插件中):

代码语言:javascript
复制
    roll() {
        const editor = atom.workspace.getActiveTextEditor();
        const regex = [
            /(\+|\-){1}([\d]+)/i,
            /([\d]+)d([\d]+)(?:([\+|\-]){1}([\d]+))*/i,
            /STAT[S]*(?:(?:[\:](?<method>(\d)))?(?:[\-](?<count>(\d)+))*)*/i
        ];

        if (editor) {
            // attempt to select the dice roll
            let selection = editor.getSelectedText();
            // if the selection failed, try selection another way.
            if (selection.length < 1) {
                editor.selectWordsContainingCursors();
                atom.commands.dispatch(atom.views.getView(editor), 'bracket-matcher:select-inside-brackets');
                selection = editor.getSelectedText();
            }
            // increase size of selection by 1, both left and right. (selects brackets)
            let range = editor.getSelectedBufferRange();
            let startColumn = range.start.column -1;
            let endColumn = range.end.column +1;
            editor.setSelectedBufferRange([[range.start.row, startColumn],[range.end.row, endColumn]]);
            // trim any whitespace from the selection
            selection.trim();

            /*
                regex pattern matching to determine the
                type of roll.
             */
             if (matches = selection.match(regex[0])) {                          // 1d20 roll; attack and ability checks
                type = 'check';
             } else if (matches = selection.match(regex[1])) {                   // typically a damage dice roll
                type = 'dmg';
             } else if (matches = selection.match(regex[2])) {                   // used for stat generation
                console.log(matches);
             } else {
                console.log('Cannot determine a suitable use.');
             }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-18 17:52:22

您可以使用

代码语言:javascript
复制
/STATS?(?::(?<method>\d)(?:-(?<count>\d+))?)?/gi

regex演示。详细信息

  • STATS? - STATSSTAT
  • (?::(?<method>\d)(?:-(?<count>\d+))?)? -可选的出现
    • : -一个冒号
    • (?<method>\d) -组“方法”:一个单数
    • (?:-(?<count>\d+))? -可选的出现
      • - -a连字符
      • (?<count>\d+) -组“计数”:一个或多个数字。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65778235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档