简体   繁体   English

Javascript使用正则表达式替换

[英]Javascript Replace using Regex

I want to replace start from @ to º with 0 below is my string 我想从替代开始@º0下面是我的字符串

I try its working only for 2 pair but not working for 3 etc pair 我尝试它只工作2对但不适用于3对等

Example 01: 例01:

Input Data 输入数据

@8~Cº + @9~Cº

Output 产量

0 + 0

Example 02: 例02:

Input Data 输入数据

@11~Cº + @12~P1º - @13~Fº

Output 产量

0+0+0

Below is my code 以下是我的代码

var tempRes = "@11~Cº + @12~P1º - @13~Fº";
tempRes = tempRes.replace(/@[0-9]~[A-Z]º/i,parseFloat(0));

You can do: 你可以做:

var s = '@11~Cº + @12~P1º + @13~Fº'
var r = s.replace(/@[^º]+º/g, 0);
//=> 0 + 0 + 0

EDIT: To remove spaces also 编辑:也删除空格

var r = s.replace(/\s*@[^º]+º\s*/g, 0);
//=> 0+0+0

you can use this regular expression to catch what you want 你可以使用这个正则表达式来捕捉你想要的东西

@.+?º

try this demo 试试这个演示

Demo 演示

to remove spaces use this regex 删除空格使用此正则表达式

\s*@.+?º\s*

try this Demo 试试这个演示

var input = '@11~Cº + @12~P1º + @13~Fº'
var output = input.replace(/\s*@.+?º\s*/g, 0)

I would use this regex in case you have multiple lines in your input: 如果您的输入中有多行,我会使用此正则表达式:

[ ]*@[^º\n]*º[ ]*

See demo 演示

Explanation: 说明:

  • [ ]* - Optional space(s) [ ]* - 可选空间
  • @ - A @ symbol @ - 一个@符号
  • [^º\\n]* - 0 or more symbols other than º and a line break [^º\\n]* -比其他0或更多个符号º和换行
  • [ ]* - Optional space(s) [ ]* - 可选空间

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

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