为什么这个正则表达式也匹配空格?

问题描述 投票:0回答:1

我有以下正则表达式

const stringPattern = "[a-zA-Z0-9]*";

const stringRegex = new RegExp(stringPattern, "g");

const str = "there are 33 states and 7 union territory in india.";

const matches = str.match(stringRegex);
console.log({matches});

为什么这个结果在正则表达式中也包含空格,没有使用

\s
 
。我们如何排除空格?

[
    "there",
    "",
    "are",
    "",
    "33",
    "",
    "states",
    "",
    "and",
    "",
    "7",
    "",
    "union",
    "",
    "territory",
    "",
    "in",
    "",
    "india",
    "",
    ""
]

javascript regex
1个回答
0
投票

这是因为

*
是一个量词,允许出现零次,这意味着它也可以匹配空字符串,将其更改为
+
,这是一个或多个出现的量词

const stringPattern = "[a-zA-Z0-9]+"; 
const stringRegex = new RegExp(stringPattern, "g");
const str = "there are 33 states and 7 union territory in india.";
const matches = str.match(stringRegex);
console.log({ matches });

© www.soinside.com 2019 - 2024. All rights reserved.