javascript - javascript提取两个标记之间的空格
问题描述
我,我尝试选择两个标记之间的所有空格(空格和制表符)。我的正则表达式是:
/(?<=start)(\s+)(?=end)/gi
示例字符串是:
this is a start marker with some words and end marker.
错误在哪里?此致。
解决方案
正则表达式的问题在于,当这两个标记之间的字符完全是空格时,它只会在两个标记之间选择空格。
请参阅以下正则表达式演示。
可能有一种更聪明的方法来完成你需要的,但我想到的最简单的方法是首先选择开始和结束标记之间的所有文本,因为这样做很容易:
/(?<=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);
同样,首先选择开始和结束标记之间的所有文本,并从该文本中替换空白。
推荐阅读
- android - 如何在辅助构造函数kotlin中访问主构造函数参数
- reactjs - material-ui:找不到模块:'./AccessAlarm'
- c# - Modbus TCP 通讯 C#
- c++ - 将二维向量传递给类
- javascript - 如何避免在使用 es6 的反应中使用绑定?
- kubernetes - gRPC 流式实例间通信
- android - 如何在 Delphi 10.3.3 in App for Android 中一起共享图像和文本
- azure-pipelines - 在类似于 MS 托管配置的 prem 代理上设置
- postgresql - 如何在不丢失openproject数据的情况下将postgresql数据库从10升级到12
- c# - WebRequest 异步 asp.net-mvc