Three moments:

  • join array items with | without side spaces
  • enclose regex alternation group into parentheses (...|...)
  • specify word boundary \b to match a separate words

var removeUselessWords = function(txt) {
    var uselessWordsArray = 
        [
          "a", "at", "be", "can", "cant", "could", "couldnt", 
          "do", "does", "how", "i", "in", "is", "many", "much", "of", 
          "on", "or", "should", "shouldnt", "so", "such", "the", 
          "them", "they", "to", "us",  "we", "what", "who", "why", 
          "with", "wont", "would", "wouldnt", "you"
        ];
			
	  var expStr = uselessWordsArray.join("|");
	  return txt.replace(new RegExp('\\b(' + expStr + ')\\b', 'gi'), ' ')
                    .replace(/\s{2,}/g, ' ');
  }

var str = "The person is going on a walk in the park. The person told us to do what we need to do in the park";
  
console.log(removeUselessWords(str));

Answer from RomanPerekhrest on Stack Overflow
Top answer
1 of 2
13

Three moments:

  • join array items with | without side spaces
  • enclose regex alternation group into parentheses (...|...)
  • specify word boundary \b to match a separate words

var removeUselessWords = function(txt) {
    var uselessWordsArray = 
        [
          "a", "at", "be", "can", "cant", "could", "couldnt", 
          "do", "does", "how", "i", "in", "is", "many", "much", "of", 
          "on", "or", "should", "shouldnt", "so", "such", "the", 
          "them", "they", "to", "us",  "we", "what", "who", "why", 
          "with", "wont", "would", "wouldnt", "you"
        ];
			
	  var expStr = uselessWordsArray.join("|");
	  return txt.replace(new RegExp('\\b(' + expStr + ')\\b', 'gi'), ' ')
                    .replace(/\s{2,}/g, ' ');
  }

var str = "The person is going on a walk in the park. The person told us to do what we need to do in the park";
  
console.log(removeUselessWords(str));

2 of 2
2

May be this is what you want:

   //Remove all instances of the words in the array
  var removeUselessWords = function(txt) {

	var uselessWordsArray = 
        [
          "a", "at", "be", "can", "cant", "could", "couldnt", 
          "do", "does", "how", "i", "in", "is", "many", "much", "of", 
          "on", "or", "should", "shouldnt", "so", "such", "the", 
          "them", "they", "to", "us",  "we", "what", "who", "why", 
          "with", "wont", "would", "wouldnt", "you"
        ];
			
	var expStr = uselessWordsArray.join("\\b|\\b");
	return txt.replace(new RegExp(expStr, 'gi'), '').trim().replace(/ +/g, ' ');
  }

  var str = "The person is going on a walk in the park. The person told us to do what we need to do in the park";
  
  console.log(removeUselessWords(str));

//The result should be: "person going walk park. person told need park."

🌐
UiPath Community
forum.uipath.com › help › studio
Regex > Replace Multiple words from input string - Studio - UiPath Community Forum
February 17, 2022 - Hi There, I have a string #abc #bbc #xyz to be removed from string of(Note: #abc #bbc #xyz will be dynamic text and not static ) #abc #bbc #xyz #testcricket #football #basketball I am using regex replace activity by replacing with " ", it works when replacing only single word.
Discussions

Remove multiple words from a string
Hello, I have a situation where I need to remove business entity types from a list of customer names. I have a list of 195 of these words/abbreviations (i.e. Inc, Co, Corp, LLC). In the String Manipulation node, I can choose Remove, but I prefer to use Replace because I have the ability to ... More on forum.knime.com
🌐 forum.knime.com
1
0
March 18, 2021
Regular Expressions - excluding multiple words with regexr - Statalist
Dear Forum Members, I recently came across an issue when trying to replace multiple words (by nothing, i.e., I need to exclude the words). In short, I wish to More on statalist.org
🌐 statalist.org
November 24, 2020
A regex method to remove a line with a certain word?

You say 'comments', so I assume you are using the bulk edit metadata search tab, searching the comments field - correct? If yes, be very careful, this is so powerful it can ruin your library - work on a copy. (If you're not in the bulk edit metadata, but in the Editor, the following should still work.)(And if you are in the main Editor, be careful to limit this to the current file, or marked text, or it will do the entire book.)

That gets tricky, depending on what you mean by a 'line'. A sentence, perhaps defined by 'spaceCapital then some words then Periodspace' ? For that you might try something like:

" [A-Z].*?yourword.*?\. " - without the quotes, they just show the space characters at the ends. Make sure case sensitive is checked. Replace with nothing. (Try with and without the first space - if your sentence starts a paragraph it will have no leading space.)

If a 'line' is actually a paragraph, try a similar thing only with <p>.*?yourword.*?</p> (And if the paragraphs have some class selector you have to include that, like <p class="something">. Look at the html source tab of the comments to see what you actually have.) This might remove several sentences.

But you also say "using the name they start with" - meaning the first word? Yet your example is not that way. If it is indeed the first word, change the string to something like "yourword.*?\. " or <p>yourword.*?</p>

And because this sort of search is VERY wide open, don't do a "replace all" until you are really sure it does what you want and nothing more. Much safer to step through one at a time.

More on reddit.com
🌐 r/Calibre
6
5
July 19, 2021
awk - Remove multiple strings from file on command line, high performance - Unix & Linux Stack Exchange
Perl regexes are capable of becoming pretty big, and a single regex would allow you to modify the input file in a single pass. Here, I'm using /usr/share/dict/words as an example for building a huge regex, mine has ~99k lines and is ~1MB big. More on unix.stackexchange.com
🌐 unix.stackexchange.com
🌐
Statalist
statalist.org › forums › forum › general-stata-discussion › general › 1583166-regular-expressions-excluding-multiple-words-with-regexr
Regular Expressions - excluding multiple words with regexr - Statalist
November 24, 2020 - For other who come across this topic at a later date, the essence of post #7 is that there were two problems with the code in post #4. First, the evaluated local macro `files' needs to be enclosed in quotation marks to create a string constant; otherwise Stata will try to interpret it as a variable name. Second, regexr() will only replace the first match; ustrregexa() will replace all matches, another advantage to Stata's Unicode regular expression functions.
🌐
Reddit
reddit.com › r/calibre › a regex method to remove a line with a certain word?
r/Calibre on Reddit: A regex method to remove a line with a certain word?
July 19, 2021 -

As the title says. I have a file that contains way too many comments and I want to remove them using the name they start with. So basically I'm looking for regex or regex function that allows searching for a word then after finding that word it deletes the whole line it is in. For example: 1 Words words words 2 Words test words If I look for the word "test," it would delete the entire line 2, "Words test words". Anyone know a way to do this?

Top answer
1 of 2
2

You say 'comments', so I assume you are using the bulk edit metadata search tab, searching the comments field - correct? If yes, be very careful, this is so powerful it can ruin your library - work on a copy. (If you're not in the bulk edit metadata, but in the Editor, the following should still work.)(And if you are in the main Editor, be careful to limit this to the current file, or marked text, or it will do the entire book.)

That gets tricky, depending on what you mean by a 'line'. A sentence, perhaps defined by 'spaceCapital then some words then Periodspace' ? For that you might try something like:

" [A-Z].*?yourword.*?\. " - without the quotes, they just show the space characters at the ends. Make sure case sensitive is checked. Replace with nothing. (Try with and without the first space - if your sentence starts a paragraph it will have no leading space.)

If a 'line' is actually a paragraph, try a similar thing only with <p>.*?yourword.*?</p> (And if the paragraphs have some class selector you have to include that, like <p class="something">. Look at the html source tab of the comments to see what you actually have.) This might remove several sentences.

But you also say "using the name they start with" - meaning the first word? Yet your example is not that way. If it is indeed the first word, change the string to something like "yourword.*?\. " or <p>yourword.*?</p>

And because this sort of search is VERY wide open, don't do a "replace all" until you are really sure it does what you want and nothing more. Much safer to step through one at a time.

2 of 2
2

AvidEReader has some excellent points and if you're using the Calibre editor to edit an ePub, there is probably no better advice.

However, you did say "file" and gave an example "line", so perhaps you're looking at lines in a .txt file that is not inside an epub (and therefore compressed), and not embedded in html paragraphs. If that's the case, I'd recommend the sed command. It's a command-line stream editor that works line-by-line on a text file.

The command sed '/test/d' a-copy-of-your-data-file.txt would do what you say you want.

  • the command passed to sed is enclosed in single quotes

    • "test" is the text you want to match

    • "/" and "/" set off the data from the command that will work on that data

    • "d" means "delete this line".

  • "a-copy-of-your-data-file.txt" is a copy of your file. sed will work on any ascii file -- it does not need a suffix -- please do use a copy, not your original file: sed's work is not reversible. It is only too easy to make a typo and there's no going back.

Oh yes -- I didn't ask which OS you use, but sed is available in linux and macOS, and Windows 10 via Windows Subsystem for Linux, so it's probably waiting for you now. Here's a link to the sed manual:

Good luck and take care.

Top answer
1 of 1
2

How big is your hitfile exactly? Could you show some actual examples of what you're trying to do? Since you haven't provided more details on your input data, this is just one idea to try out and benchmark against your real data.

Perl regexes are capable of becoming pretty big, and a single regex would allow you to modify the input file in a single pass. Here, I'm using /usr/share/dict/words as an example for building a huge regex, mine has ~99k lines and is ~1MB big.

use warnings;
use strict;
use open qw/:std :encoding(UTF-8)/;

my ($big_regex) = do {
    open my $wfh, '<', '/usr/share/dict/words' or die $!;
    chomp( my @words = <$wfh> );
    map { qr/\b(?:$_)\b/ } join '|', map {quotemeta}
        sort { length $b <=> length $a or $a cmp $b } @words };

while (<>) {
    s/$big_regex//g;
    print;
}

I don't need regex, I only need to compare pure/exact strings against a hash (for speed). i.e. "pine" should not match "pineapple", but it should match "(pine)".

If "pine" should not match "pineapple", you need to check the characters before and after the occurrence of "pine" in the input as well. While certainly possible with fixed string methods, it sounds like the regex concept of word boundaries (\b) is what you're after.

Is there an elegant, high-performance one-liner way ... for my workflow I'd prefer a simple command to my script.

I'm not sure I agree with this sentiment. What's wrong with perl script.pl? You can use it with shell redirections/pipes just like a one-liner. Putting code into a script will unclutter your command line, and allow you to do complex things without trying to jam it all into a one-liner. Plus, short does not necessarily mean fast.

Another reason you might want to use a script is if you have multiple input files. With the code I showed above, building the regex is fairly expensive, so calling the script multiple times will be expensive - processing multiple files in a single script will eliminate that overhead. I love the UNIX principle, but for big data, calling multiple processes (sometimes many times over) and piping data between them is not always the most efficient method, and streamlining it all in a single program can help.


Update: As per the comments, enough rope to shoot yourself in the foot 😉 Code that does the same as above in a one-liner:

perl -CDS -ple 'BEGIN{local$/;($r)=map{qr/\b(?:$_)\b/}join"|",map{quotemeta}sort{length$b<=>length$a}split/\n/,<>}s/$r//g' /usr/share/dict/words input.txt
Find elsewhere
🌐
MUI Stack
muhimasri.com › blogs › how-to-replace-multiple-words-and-characters-in-javascript
How to Replace Multiple Words and Characters in JavaScript
December 6, 2021 - We can further improve this by creating a list of words dynamically from the correction object as follows: const reg = new RegExp(Object.keys(correction).join("|"), "g"); str = str.replace(reg, (matched) => correction[matched]);
🌐
Alvin Alexander
alvinalexander.com › java › how-to-use-multiple-regex-patterns-replaceall-strings-in-java
How to use multiple regex patterns with replaceAll (Java String class) | alvinalexander.com
February 3, 2024 - Next, what I want to do is remove all of these characters from the strings in that array: ... scala> val cleanWords = words.map(_.replaceAll("[\\.$|,|;|']", "")) cleanWords: Array[String] = Array(My, dog, ate, all, of, the, cheese, why, I, dont, know) ... The combination of the brackets and pipe characters is what makes this work. It’s often hard to read regex patterns, so it may help to look at that multiple ...
🌐
MathWorks
mathworks.com › text analytics toolbox › text data preparation
regexprep - Replace text in words of documents using regular expression - MATLAB
If both replace and expression are cell arrays of character vectors, then they must contain the same number of elements. regexprep pairs each replace element with its corresponding element in expression. The replacement text can include regular characters, special characters (such as tabs or new lines), or replacement operators, as shown in the following tables. ... Output documents, returned as a tokenizedDocument array. Text Analytics Toolbox provides functions for common text preprocessing steps. For example, to remove punctuation and symbol characters, use erasePunctuation or to remove stem words using the Porter stemmer, use normalizeWords.
🌐
litsupporttips
litigationsupporttipofthenight.com › single-post › regex-search-to-find-and-replace-multiple-strings
Regex search to find and replace multiple strings
July 30, 2023 - In order to find and replace multiple strings using regular expression you can use this format: Find: (FindA)|(FindB)|(FindC)...Replace: (?1ReplaceA)(?2ReplaceB)(?3ReplaceC)...However if the operation is run this way it will not take word boundaries ...
🌐
Super User
superuser.com › questions › 1545303 › regex-how-to-delete-word-that-contains-specific-keyword
notepad++ - Regex - how to delete word that contains specific keyword - Super User
Essentially, once detecting the "www" combination it will remove anything around it until encountering a space on either side. This includes commas, periods etc, unless you add them to the square brackets as well. Applying the pattern to every row depends on which software is running the regex search; In np++ mentioned in the tags, it's under find -> replace -> set to regular expression, replace all.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 481822 › replacing-multiple-words-with-regex
java - Replacing multiple words with Regex [SOLVED] | DaniWeb
Troubleshooting tips: use \\b for whole-word matches, escape keys when building alternation, call Pattern.compile once if you reuse it, and prefer the chain for 2–3 replacements (clear and fast), but prefer the single-pass Map approach for large dictionaries or huge texts. I'm not entirely clear on what you are trying to do. can you elaborate a bit on it, please? — stultuske 1,129 Jump to Post · I'm no regex expert, but my guess is that you can't, or, if you can, it's ludicrously complex.
🌐
Super User
superuser.com › questions › 1686765 › regex-match-and-delete-2-words-before-and-after-the-specified-word
notepad++ - Regex: Match and delete 2 words before and after the specified word - Super User
November 10, 2021 - If, for you, word contains only letters and soeme punctuation like ', use [a-zA-Z']+ instead of \S+. ... Lights, camera, open source! Black box AI drift: AI tools are making design decisions nobody asked for · 0 Regex: Match/Delete everything on a line except parenthesis (keep the parentheses and delete the rest of the words on the line)
🌐
Ablebits
ablebits.com › ablebits blog › excel › regex › regex to remove certain characters or text in excel
Excel Regex to remove certain characters or text from strings
August 22, 2023 - The default is "all matches" - when the instance_num argument is omitted, all found matches are removed. To delete a specific match, define the instance number. In the below strings, suppose you want to delete the first order number. All such numbers start with the hash sign (#) and contain exactly 5 digits. So, we can identify them using this regex: ... The word boundary \b specifies that a matching substring cannot be part of a bigger string such as #10000001.
🌐
Laserfiche Answers
answers.laserfiche.com › questions › 108369 › Remove-Word-using-Regular-Expression
Remove Word using Regular Expression - Laserfiche Answers
It should be removed anywhere in the string. This solves my problem temporarily but i would like to use regular expression instead. ... It's not possible to do it with a single regular expression. The one above will work for the case where the word "other" is present.