对于ECMAScript的正则表达式,我需要一点帮助。我目前使用的regex几乎可以按需要工作,但是有一个小问题。我需要匹配以下几点:
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-骰子插件中):
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.');
}发布于 2021-01-18 17:52:22
您可以使用
/STATS?(?::(?<method>\d)(?:-(?<count>\d+))?)?/gi见regex演示。详细信息
STATS? - STATS或STAT(?::(?<method>\d)(?:-(?<count>\d+))?)? -可选的出现: -一个冒号(?<method>\d) -组“方法”:一个单数(?:-(?<count>\d+))? -可选的出现- -a连字符(?<count>\d+) -组“计数”:一个或多个数字。https://stackoverflow.com/questions/65778235
复制相似问题