我有以下正则表达式
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",
"",
""
]
这是因为
*
是一个量词,允许出现零次,这意味着它也可以匹配空字符串,将其更改为+
,这是一个或多个出现的量词
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 });