用于匹配数字和特殊字符失败的正则表达式

RegEx for matching digits and failing on special chars

我下面的正则表达式匹配数字后带有此 字符的所有内容。我希望仅当存在 时才能够匹配,但如果其后跟

则不能匹配
\(\d{1,}(?:\,?\d{3})*(?:\.\d+)?[ ]?)(!千伏|!千吨|千)\

目前:

220千伏 (match '220千')
220千吨 (match '220千')
220千 (match '220千')

预计:

220千伏 (no match)
220千吨 (no match)
220千 (match '220千')

我的猜测是您可能想要一个列表来排除某些内容并具有其他特定字符,可能类似于:

\d{1,}(?:\,?\d{3})*(?!千伏|千吨)(?:千)

正则表达式

您可以 design/modify/change 在 regex101.com 中表达您的表情。

正则表达式电路

您可以在 jex.im 中可视化您的表情:

JavaScript 测试

const regex = /\d{1,}(?:\,?\d{3})*(?!千伏|千吨)(?:千)/gm;
const str = `220千伏
220千吨
220千`;
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.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

此外,您可能不想转义 non-metachars,就像 Barmar 建议的那样,您可以修改表达式的这一部分:

\d{1,}(?:\,?\d{3})*

请参阅下面的正则表达式工作版本。

主要思想是使用千(?![伏吨]),这是一个文字后跟一个否定的look-ahead断言(而[]只是一个字符 class,像往常一样)。它匹配千,但前提是后面没有伏或吨。

(我还删除了多余的括号,将 {1,} 更改为 +,并将匹配锚定到字符串的开头。如果您不希望这样,请至少考虑使用开头的 \b(单词边界)锚点。)

const inputs = [
  '220千伏',
  '220千吨',
  '220千',
];

for (const str of inputs) {
  console.log(
    str + (
      /^\d+(?:,\d{3})*(?:\.\d+)?[ ]?千(?![伏吨])/.test(str)
        ? ' (match)'
        : ' (no match)'
    )
  );
}