如何使用正则表达式替换指定字符串以外的所有内容 [英] How to replace everything but a specified string using regex

查看:98
本文介绍了如何使用正则表达式替换指定字符串以外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找并解决这个问题,但是我没有任何运气.

I've been looking through and out of stackoverflow for this, but I haven't had any luck.

我要使用的字符串是"xbananay",其中"x"和"y"可以是任意长度的字母或数字的任意组合.因此,我的字符串可以只是"qrstbananag",但也可以是"abcbanana12345".

The string I want to work with is "xbananay", where 'x' and 'y' can be any random combination of letters or numbers with any length. So my string could simply be "qrstbananag", but it could also be "abcbanana12345" for example.

我想使用并且仅使用的javascript替换功能来替换所有但香蕉".我已经有了一些可以找到香蕉的正则表达式,但是当我想查找其他所有内容时,按预期的替换功能将替换我要查找的内容.示例:

I want to use, and only use, javascript's replace function to replace everything BUT "banana". I already have some regex that can find banana, but the replace function, as intended, will replace what I am looking for, when I want to find everything else. Example:

var fullString = "qrstbananag"
var strippedBanana = fullString.replace(/(?:banana)/g, ''); //returns qrstg

我也有一个正则表达式,ALMOST可以为我提供所需的内容,但字符串"banana"中包含所有字符.另一个例子:

I also have a regex expression that ALMOST gets me what I am looking for, but includes all characters in the string "banana". Another example:

var fullString2 = "abcbanana12345"
var strippedBanana = fullString2.replace(/[^(?:banana)]/g, ''); //returns abbanana

我如何仅使用替换功能来完成此操作?预先感谢.

How might I accomplish this using only the replace function? Thanks in advance.

推荐答案

您可以使用:

var test = 'abcbananadefbananaghi';

var result = test.replace(/(banana)|[^]/g, '$1');

console.log(result);

事情是匹配 banana 并用 $ 1 将其放回结果中.如果香蕉不匹配,则下一个字符( [^] 也与换行符匹配)不会被捕获到捕获组中,因此不会包含在捕获组中. $ 1 .

The thing is to match banana and put it back in the result with $1. When banana doesn't match, the next character ([^], which also matches newlines) is not captured in a capture group, and so does not get included in the $1.

除了 [^] ,您还可以使用 [\ S \ s] :相同的行为.

Instead of [^] you can also use [\S\s]: same behaviour.

您第二次尝试使用

[^(?:banana)]

但是请注意,在类中(在 [...] 之间)中的字符比其他情况下会在字面上得到更多的对待.因此,(?:被视为三个单独的字符,而 banana 的字符也被视为.您实际上是在说:删除不属于这些字符的任何字符:()?: abn .

But be aware that the characters in a class (between [...]) are treated more literally than they would otherwise. So (?: is treated as three separate characters, and so are the characters of banana. You are in fact saying: remove any character that is not any of these: ()?:abn.

这篇关于如何使用正则表达式替换指定字符串以外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆