MokiNex
MokiNex

Reputation: 889

RegExp to Parse and replace specific Words

I want to delete the words Fwd: and [ProQuest Alert] (the string that's between square brackets) and not the Fwd: that's Part of the string text

Explanation:

\[(.*?)\] -> to extract text between square brackets (regex globally)

The \b denotes a word boundary, which is the (zero-width) spot between a character in the range of "word characters" ([A-Za-z0-9_]) and any other character

This my Regexp:

 ?\b(Fwd:)|\[(.*?)\] ?

Demo: https://regex101.com/r/qlTpWb/7

    var str = "Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd:";
    str = str.replace(/ ?\b(Fwd:)|\[(.*?)\] ?/gi, ' ');
    console.log(str)

Upvotes: 3

Views: 715

Answers (2)

Al3x_M
Al3x_M

Reputation: 214

And this regular expression?

var str = "Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd:";
str = str.replace(/\b(Fwd:)(\s|$)|\[(.*?)\]/gi, ' ');
console.log(str)

I only tried it in regex101.com.

Upvotes: 1

Jan
Jan

Reputation: 43189

One solution would be to match what you don't want and to capture what you do want to be removed:

keep_me1|keep_me2|(delete_me)

See a demo on regex101.com.


As lookbehinds and (*SKIP)(*FAIL) are not supported, you need some programming functionality:

let data = 'Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd: fwd:';
let regex = /\w+:\w+|(\[[^\[\]]+\]|\bFwd:)/gi

data = data.replace(regex, function(match, group1) {
    if (typeof(group1) == "undefined") {
        return match;
    } else {
        return '';
    }
});
console.log(data);

Upvotes: 1

Related Questions