简体   繁体   English

使用正则表达式将字符替换为特定字符

[英]Replace chars up to a specific char using Regex

I have a string "000-2.50" or "00-12.50" or "0-120.50" and I want to replace the zeros up to the minus sign "-" with an @ char. 我有一个字符串“ 000-2.50”或“ 00-12.50”或“ 0-120.50”,我想用一个@字符替换零直到负号“-”。

I want to end up with "@@@-2.50" or "@@-12.50" or "@-120.50". 我想以“ @@@-2.50”或“ @@-12.50”或“ @ -120.50”结尾。 How do I achieve that using Regex? 如何使用正则表达式实现这一目标?

Look for all zeros that are followed by a dash using a positive lookahead: 使用正向先行查找所有零后跟一个破折号:

Method 1: 方法1:

0(?=[^-]*-)

JS Code: JS代码:

 console.log( "000-2.50".replace(/0(?=[^-]*-)/g, "@") ); 

Method 2 方法2

Or if you only want leading zeros: 或者,如果您只想要前导零:

 console.log( "000-2.50".replace(/^0+(?=-)/g, function(match) { return "@".repeat(match.length); }) ) 

To replace each 0 from beginning of the string, how about using the sticky flag y 要从字符串开头替换每个0 ,如何使用粘滞标记y

 var str = '000-2.50'; var res = str.replace(/0/gy, '@'); console.log(res); 

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

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