简体   繁体   English

正则表达式替换文本行中的前导空格

[英]regex replace leading spaces in text line

I have a string:我有一个字符串:

"    Some text here\n   Some new line text here"

I need to get from it:我需要从中得到:

"----Some text here\n---Some new line text here"

So that each space in the beginning of the line (string or line break symbol) would be replaces with say dash.这样行首的每个空格(字符串或换行符)都将被替换为破折号。

Not sure how to implement it the simplest way.不确定如何以最简单的方式实现它。

Try following:尝试以下操作:

> "    Some text here\n   Some new line text here".replace(/^\s+/gm, '----')
"----Some text here\m----Some new line text here"

or:或:

"    Some text here\n   Some new line text here".replace(/^\s+/gm, function(spaces) { return spaces.replace(/./g, '-'); } )
"----Some text here\m----Some new line text here"

There is a way to match each leading pattern individually using a lookbehind, but this is an ECMAScript 2018+ only compatible solution.有一种方法可以使用lookbehind 单独匹配每个前导模式,但这是仅兼容 ECMAScript 2018+ 的解决方案。

Lookbehind adoption can be tracked here , see RegExp Lookbehind Assertions .可以在此处跟踪后视采用情况,请参阅RegExp 后视断言 Right now, they are supported by Chrome, Edge, Opera including Opera Mobile, Samsung Internet, and Node.js.目前,Chrome、Edge、Opera 包括 Opera Mobile、Samsung Internet 和 Node.js 都支持它们。 Firefox is adding "support for the dotAll flag, lookbehind references, named captures, and Unicode escape sequences" to the SpiderMonkey RegExp engine on June 30, 2020. Firefox将于 2020 年 6 月 30 日向 SpiderMonkey RegExp 引擎添加“对 dotAll 标志、后视引用、命名捕获和 Unicode 转义序列的支持”

Solution for the current scenario:当前场景的解决方案:

.replace(/(?<=^\s*)\s/gm, '-')

Here, /(?<=^\\s*)\\s/gm matches any whitespace char ( \\s ) that is immediately preceded with any 0+ whitespace chars at the start of the line (see the (?<=^\\s*) positive lookbehind).这里, /(?<=^\\s*)\\s/gm匹配任何紧跟在行开头的任何 0+ 空白字符之前的空白字符 ( \\s )(参见(?<=^\\s*)正面回顾)。 See this regex demo .请参阅此正则表达式演示

NOTE : since \\s matches line break chars, all empty lines will be replaced with a hyphen, too.注意:由于\\s匹配换行符,所有空行也将替换为连字符。 If empty lines must be preserved use [^\\S\\n\\v\\f\\r\
\
 instead of \\s :如果必须保留空行,请使用[^\\S\\n\\v\\f\\r\
\
而不是\\s

.replace(/(?<=^[^\S\n\v\f\r\u2028\u2029]*)[^\S\n\v\f\r\u2028\u2029]/gm, '-')

where [^\\S\\n\\v\\f\\r\
\
] matches any whitespace char other than linefeed, vertical tab, form feed, carriage return, line and paragraph separators.其中[^\\S\\n\\v\\f\\r\
\
]匹配除换行符、垂直制表符、换页符、回车符、行和段落分隔符以外的任何空白字符。 See this regex demo .请参阅此正则表达式演示

JS demo: JS演示:

 // Any whitespace chars console.log(" Some text here\\n\\n Some new line text here" .replace(/(?<=^\\s*)\\s/gm, '-')) // Only horizontal whitespace console.log(" Some text here\\n\\n Some new line text here" .replace(/(?<=^[^\\S\\n\\v\\f\\r\
\
]*)[^\\S\\n\\v\\f\\r\
\
]/gm, '-'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM