简体   繁体   中英

find and remove words matching a substring in a sentence

Is it possible to use regex to find all words within a sentence that contains a substring?

Example:

var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";

I need to find all words in this sentence which contains 'undefined' and remove those words.

Output should be "hello my number is ";

FYI - currently I tokenize (javascript) and iterate through all the tokens to find and remove, then merge the final string. I need to use regex. Please help.

Thanks!

You can use:

str = str.replace(/ *\b\S*?undefined\S*\b/g, '');

RegEx Demo

It certainly is possible.

Something like start of word, zero or more letters, "undefined", zero or more letters, end of word should do it.

A word boundary is \\b outside a character class, so:

\b\w*?undefined\w*?\b

using non-greedy repetition to avoid the letter matching tryig to match "undefined" and leading to lots of backtracking.

Edit switch [a-zA-Z] to \\w because the example includes numbers in the "words".

\S*undefined\S*

Try this simple regex.Replace by empty string .See demo.

https://www.regex101.com/r/fG5pZ8/5

Since there are enough solutions with regular expressions, here is another one - using arrays and simple function that finds occurrence of a string in a string :)

Even though the code looks more "dirty", it actually works faster than regular expression, so it might make sense to consider it when dealing with LARGE strings

    var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
    var array = sentence.split(' ');
    var sanitizedArray = [];

    for (var i = 0; i <= array.length; i++) {
        if (undefined !== array[i] && array[i].indexOf('undefined') == -1) {
            sanitizedArray.push(array[i]);
        }
    }

    var sanitizedSentence = sanitizedArray.join(' ');

    alert(sanitizedSentence);

Fiddle: http://jsfiddle.net/448bbumh/

你可以像这样使用str.replace函数

str = str.replace(/undefined/g, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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