【发布时间】:2021-01-18 16:16:14
【问题描述】:
我需要一些有关 ECMAScript 正则表达式的帮助。我目前使用的正则表达式几乎可以按要求工作,但有一个小问题。我需要匹配以下内容:
STAT 或 STATS 不分大小写。此外,后面可能还有符号和数字。
示例:
stats:3-2 是匹配项。
stats:5 是匹配项。
stats-4 是部分匹配,但 '-4' 应该被忽略。
如前所述,我正在使用的当前正则表达式几乎可以正常工作,如下所示:
/STAT[S]*(?:(?:[\:](?<method>(\d)))(?:[\-](?<count>(\d)+))*)*/ig
此模式使用 regex101,实际上匹配所有条件并忽略以下示例中的 -4:stats-4,同时匹配单词“stats”。
但是,当我尝试在我正在编辑的插件中使用此模式时,就会出现问题。它目前只匹配stat、stats、stat:2,但不匹配stat:3-2、stat-4(应该匹配'stat'但忽略'-4')。
我知道模式可能有点混乱,但我不擅长创建正则表达式。
具体用法(在 atom rpg-dice 插件中):
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.');
}
【问题讨论】:
-
/STATS?(?::(?<method>\d)(?:-(?<count>\d+))?)?/gishould work 如果插件支持最新的 ECMAScript 规范。 -
我刚试过,还是不行。基本上,如果我添加 - 后跟一个数字,它就不起作用。
-
@JLDNAdmin 因为你的第一个
\d前面没有可选的-,就像第二个一样。 -
@r3wt 你能告诉我吗?我没有关注。
-
试试这个:
/STAT[S]*(?:(?:[\:](?<method>(\d)))?(?:[\-](?<count>(\d)+))*)*/ig
标签: javascript regex