首页 > 解决方案 > 一次允许一个特定字符的正则表达式

问题描述

我有一个要求,允许任何数字一次只有一个字符(W 或 D),没有顺序。

例如:2w222W2d222D2w5d

不像2wd55dw)_

我试过这样的东西,但它不工作

[^\\d][w]$.

标签: javascriptjavaregex

解决方案


这是你想要的?

/\b(\d+[dw](?![dw]))+\b/ig

编辑:请参阅上面评论中@bobblebubble 的答案以获得更好的选择。

请参阅下面或此处的片段:https ://regex101.com

const regex = /\b(\d+[dw](?![dw]))+\b/ig;
const str = `2w 55dw 222W 2d 2wd 222D 2w5d`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // The result can be accessed through the `m`-variable.
  document.write(`Found match: ${m[0]}<br>`);
}


推荐阅读