使用全局RegExp和String.prototype.replace删除所有匹配项

问题描述 投票:0回答:3

function strip(match, before, after) {
  return before && after ? ' ' : ''
}

var regex = /(^|\s)(?:y|x)(\s|$)/g

var str = ('x 1 y 2 x 3 y').replace(regex, strip)
console.log(str)

str = ('x y 2 x 3 y').replace(regex, strip)
console.log(str)

目标是删除所有出现的“x”和“y”。

第一个示例按预期工作,但第二个示例没有。

要求:

  • 解决方案必须支持删除任何长度的单词。
  • 单词之间绝不能有大于1的空格。
  • 避免删除包含“x”或“y”(必须相等)的单词。

我可以使用replace解决这个问题,还是需要一个不同的解决方案?

javascript regex string
3个回答
2
投票

您不能将相同的字符匹配两次(匹配结束时的空格字符,当子字符串连续时,在下一个匹配开始时不能再匹配一次)。

避免这种情况的一种可能方法是将( |$)更改为前瞻,检查空间而不消耗它。但是你需要改变你的方法,因为你必须在结束或开始时修剪最终的剩余空间:

var regex = /(^|\s)(?:y|x)(?!\S)/g;
var str = 'x y 2 x 3 y'.replace(regex, '').trim();

(?!\S)表示:未跟随非空格字符(如果位置后跟空格或字符串结尾,则成功)。


其他方式:您可以匹配所有连续的x和y。

function strip(match, before, after) {
    return before && after ? ' ' : ''
}

var regex = /(^|\s)(?:y|x)(?:\s(?:y|x))*(\s|$)/g;

var str = 'x y 2 x 3 y'.replace(regex, strip);

拆分字符串:

var str = 'x y 2 x 3 y'.split(/\s+/).filter(a => !['x', 'y'].includes(a)).join(' ');

0
投票

我用3个替换语句完成了它:

('x y 2 x 3 y 4 x').replace(/\b[xy]\b/g, "").replace(/\b\s\s+\b/g, ' ').replace(/^\s+|\s+$/g, "")

编辑:最后一个可以用.trim()替换


-1
投票

我解决了另一种不使用trim()的方法:

('x 1 y 2 x 3 y 4 x').replace(/(^|\s?)(?:y|x)(\s?|$)/g, strip)

function strip(match, before, after) {
  return before && after ? ' ' : ''
}

console.log("With 1: ", ('x 1 y 2 x 3 y 4 x').replace(/(^|\s?)(?:y|x)(\s?|$)/g, strip))

console.log("With 1: ", ('x y 2 x 3 y 4 x').replace(/(^|\s?)(?:y|x)(\s?|$)/g, strip))
© www.soinside.com 2019 - 2024. All rights reserved.