繁体   English   中英

替换正则表达式javascript

[英]Replace regular expression javascript

我有这样的字符串

|1.774|1.78|1|||||1.781|1||||||||

我应用了替换表达式

str = str.replace(/\|\|/g, '| |')

输出结果是

|1.774|1.78|1| || ||1.781|1| || || || |

但结果一定是这样的

|1.774|1.78|1| | | | |1.781|1| | | | | | | |

错误在哪里? 谢谢

你需要在这里使用前瞻来检查一个| 之后|

str = str.replace(/\|(?=\|)/g, '| ')

请参阅正则表达式演示

细节

  • \\| - 文字|
  • (?=\\|) - 匹配但不消耗下一个|的正向前瞻 char,因此将其保持在匹配之外,并且在下一次迭代期间仍可以匹配此char。

只是为了好玩,而不是使用正则表达式,您可以使用以下javascript函数:

let original = '|1.774|1.78|1|||||1.781|1||||||||';

let str = original.split('|').map((e, i, arr) => {
    // 1) if the element is not on the end of the split array...
    // 2) and if element is empty ('')
    // -> there's no data between '|' chars, so convert from empty string to space (' ')
    if (i > 0 && i < arr.length -1 && e === '') return ' ';
    // otherwise return original '|' if there is data found OR if element is on the end
    // -> of the split array
    else return e
}).join('|')

Wiktor的正则表达式很漂亮,但我只是觉得我会提供一个简单的JS版本。

暂无
暂无

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

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