首页 > 解决方案 > javascript提取两个标记之间的空格

问题描述

我,我尝试选择两个标记之间的所有空格(空格和制表符)。我的正则表达式是:

/(?<=start)(\s+)(?=end)/gi

示例字符串是:

this is a start marker with some words and end marker.

错误在哪里?此致。

标签: javascriptregex

解决方案


正则表达式的问题在于,当这两个标记之间的字符完全是空格时,它只会在两个标记之间选择空格。

请参阅以下正则表达式演示

可能有一种更聪明的方法来完成你需要的,但我想到的最简单的方法是首先选择开始和结束标记之间的所有文本,因为这样做很容易:

/(?<=start)[\s\S]*(?=end)/

在哪里

[\s\S]* matches 0 or more characters (white or non-white space characters, including the newline).

然后根据您要执行的操作,相应地处理 Group 0 字符串。例如,如果您有兴趣知道有多少空白字符,那么下面的代码片段就可以解决问题:

let text = 'this is a start marker with some words and end marker.';
let regexp = /(?<=start)[\s\S]*(?=end)/;
match = text.match(regexp); // extract text between markers
let s = match[0]; // this is extracted text
regexp = /\s/g;
let matches = s.matchAll(regexp); // match all single white space chatacters
matches = Array.from(matches);
console.log(matches.length);

您必须首先提取标记之间存在的空白和非空白字符,然后匹配所有空白字符。

相反,如果您想用空字符串替换空白字符(即去掉它们),那么以下代码段将完成此操作:

let text = 'this is a start marker with some words and end marker.';
let regexp = /(?<=start)[\s\S]*(?=end)/; // extract text between markers
function replacer(match)
{
    return match.replace(/\s+/g, '');
}
text = text.replace(regexp, replacer);
console.log(text);

同样,首先选择开始和结束标记之间的所有文本,并从该文本中替换空白。


推荐阅读