text = re.sub(r'\b(\w+)( \1\b)+', r'\1', text) #remove duplicated words in row

The \b matches the empty string, but only at the beginning or end of a word.

Answer from tom on Stack Overflow
🌐
Medium
ngsanthosh657.medium.com › how-to-remove-duplicate-words-from-given-string-using-regular-expression-with-python-b9b68a1f7ba0
How to remove duplicate words from given string using Regular expression with Python? | by Santhosh Sudhaan | Medium
June 8, 2021 - Then we start writing a function ... a argument · Inside the function we write the regex checks to check for repeated words and we pass it to a sub function which is again provided to us by “re” module....
🌐
Educative
educative.io › answers › how-to-remove-duplicate-words-from-text-using-regex-in-python
How to remove duplicate words from text using Regex in Python
\\w: This denotes a word character, i.e., [a-zA-Z_0–9]. ... \\1: This matches whatever was matched in the previous group of parentheses, which in our case is the (\w+). +: This is used to match whatever is placed before this 1 or more times. ... In line 1, we import the re package, which will allow us to use regex. In line 3, we define a function that will return text after removing the duplicate words.
Top answer
1 of 2
6

Since you were working with RegEx, I will ofer a RegEx solution.

I will also show that you need to also take care to first remove punctuation. (I will not go down the rabbit-hole of re-sinserting the punctuation back where it was!)

A RegEx solution:

import re
sentence = 'I need need to learn regex... regex from scratch!'

# remove punctuation
# the unicode flag makes it work for more letter types (non-ascii)
no_punc = re.sub(r'[^\w\s]', '', sentence, re.UNICODE)
print('No punctuation:', no_punc)

# remove duplicates
re_output = re.sub(r'\b(\w+)( \1\b)+', r'\1', no_punc)
print('No duplicates:', re_output)

Returns:

No punctuation: I need need to learn regex regex from scratch
No duplicates: I need to learn regex from scratch
  • \b : matches word boundaries
  • \w : any word character
  • \1 : replaces the matches with the second word found - the group in the second set of parentheses

The parts in parentheses are referred to as groups, and you can do things like name them and refer to them later in a regex. This pattern should recursively catch repeating words, so if there were 10 in a row, they get replaced with just the final occurence.

Have a look here for more detailed definitions of the regex patterns.

The more pythonic (looking) way

It has to be said that the groupby method has a certain python-zen feel about it! Simple, easy to read, beautiful.

Here I just show another way of removing the punctuation, making use of the string module, translating any punctuation characters into None (which removes them):

from itertools import groupby
import string

sentence = 'I need need to learn regex... regex from scratch!'

# Remove punctuation
sent_map = sentence.maketrans(dict.fromkeys(string.punctuation))
sent_clean = sentence.translate(sent_map)
print('Clean sentence:', sent_clean)

no_dupes = ([k for k, v in groupby(sent_clean.split())])
print('No duplicates:', no_dupes)

# Put the list back together into a sentence
groupby_output = ' '.join(no_dupes)
print('Final output:', groupby_output)

# At least for this toy example, the outputs are identical:
print('Identical output:', re_output == groupby_output)

Returns:

Clean sentence: I need need to learn regex regex from scratch
No duplicates: ['I', 'need', 'to', 'learn', 'regex', 'from', 'scratch']
Final output: I need to learn regex from scratch
Identical output: True

Benchmarks

Out of curiosity, I dumped the lines above into functions and ran a simple benchmark:

RegEx:

In [1]: %timeit remove_regex(sentence)
8.17 µs ± 88.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

groupby:

In [2]: %timeit remove_groupby(sentence)
5.89 µs ± 527 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

I had read that regex would be faster these days (using Python3.6) - but it seems that sticking to beautiful code pays off in this case!

Disclaimer: the example sentence was very short. This result might not scale to sentences with more/less repeated words and punctuation!

2 of 2
1

From what I understood, doing this with regex rules can be tricky and a bit slow. In python, I use this and it works perfectly :

from itertools import groupby
line_split = [k for k,v in groupby(line.split())]
🌐
Source Code Tester
sourcecodester.com › tutorial › python › 17945 › how-remove-duplicate-words-sentence-using-regular-expressions-python
How to Remove Duplicate Words from a Sentence Using Regular Expressions in Python | SourceCodester
February 26, 2025 - Learn how to remove duplicate words from a sentence using regex in Python. This step-by-step tutorial will guide you through the process with clear examples.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-duplicate-words-from-sentence-using-regular-expression
Remove duplicate words from Sentence using Regular Expression - GeeksforGeeks
July 12, 2025 - Given a string str which represents a sentence, the task is to remove the duplicate words from sentences using regular Expression in Programming Languages like C++, Java, C#, Python, etc.
🌐
YouTube
youtube.com › watch
Regex Tutorial: Find & Remove Duplicate Words in Text (Python) - YouTube
Learn how to find and remove duplicate words in text using regular expressions (regex) in Python! This beginner-friendly tutorial breaks down the process ste...
Published   September 8, 2025
🌐
HowDev
how.dev › answers › how-to-remove-duplicate-words-from-text-using-regex-in-python
How to remove duplicate words from text using Regex in Python
Use Python Regex to remove duplicate words by defining a pattern, utilizing the `re` package, and employing the `sub()` function for text preprocessing.
Find elsewhere
Top answer
1 of 2
4

you could back reference the word in your search expression:

>>> s = "server_server_dev1_check_1233.zzz"
>>> re.sub(r"(.*_)\1",r"\1",s)
'server_dev1_check_1233.zzz'

and use the "many times" suffix so if there are more than 2 occurrences it still works:

'server_server_server_dev1_check_1233.zzz'
>>> re.sub(r"(.*_)\1{1,}",r"\1",s)
'server_dev1_check_1233.zzz'

getting rid of the suffix is not the hardest part, just capture the rest and discard the end:

>>> re.sub(r"(.*_)\1{1,}(.*)(_\d+\..*)",r"\1\2",s)
'server_dev1_check'
2 of 2
3

You may use a single re.sub call to match and remove what you do not need and match and capture what you need:

re.sub(r'^([^_]+)(?:_\1)*(.*)_\d+\.\w+$', r'\1\2', s)

See the regex demo

Details

  • ^ - start of string
  • ([^_]+) - Capturing group 1: any 1+ chars other than _
  • (?:_\1)* - zero or more repetitions of _ followed with the same substring as in Group 1 (thanks to the inline backreference \1 that retrieves the text from Group 1)
  • (.*) - Group 2: any 0+ chars, as many as possible
  • _ - an underscore
  • \d+ - 1+ digits
  • \. - a dot
  • \w+ - 1+ word chars ([^.]+ will also do, 1 or more chars other than .)
  • $ - end of string.

The replacement pattern is \1\2, i.e. the contents of Group 1 and 2 are concatenated and make up the resulting value.

Python demo:

import re
rx = r'^([^_]+)(?:_\1)*(.*)_\d+\.\w+$'
strs = ["server_server_dev1_check_1233.zzz", "server_server_qa1_run_1233.xyz", "server_server_dev2_1233.qqa", "server_dev1_1233.zzz", "data_data_dev9_check_660.log"]
for s in strs:
    print(re.sub(rx, r'\1\2', s))

Output:

server_dev1_check
server_qa1_run
server_dev2
server_dev1
data_dev9_check
Top answer
1 of 3
14

You can use a regular expression to remove consecutive duplicated words in a line, however I don't think it's possible to remove duplicated words which are not consecutive (e.g dangerous, hazardous, dangerous).

Use this regex in the replace window in Notepad++, and don't forget to select "Regular expression" as the Search Mode option below:

This regex will remove all consecutive duplicated words - whether it's 2 duplicated words or 10 duplicated words consecutively: \b(\w+)(?:,\s+\1\b)+.

The exact same no-commas regex would be: \b(\w+)(?:\s+\1\b)+ (might be useful for other users).

If you want a regex specifically for only two duplicated words (doubles), use this regex: (\b\w+\b)\W+\1.

Place this regex in the Replace with box to keep one occurrence of the word (otherwise all repeated words will be removed): ${1}.

These regular expressions will fix a situation like the one you described in your question as an example. The first regex will work for every number of duplicated words (e.g dangerous, dangerous, dangerous, dangerous, hazardous), while the second version will only work for two duplicated words (e.g dangerous, dangerous, hazardous).

Note: The regular expression will only apply to the format described in the question, meaning that formats like two words, two words, anotherword, two-words, two-words, anotherword, three words expression, three words expression, anotherword won't be changed because the regex won't apply to them.

2 of 3
4

Here is a way to do the job, this will replace all duplicate words even if they are not contiguous:

  • Ctrl+H
  • Find what: (?:^|\G)(\b\w+\b),?(?=.*\1)
  • Replace with: LEAVE EMPTY
  • check Wrap around
  • check Regular expression
  • DO NOT CHECK . matches newline
  • Replace all

Explanation:

(?:^|\G)    : non capture group, beginning of line or position of last match
(\b\w+\b)   : group 1, 1 or more word character (ie. [a-zA-Z0-9_]), surrounded by word boundaries
,?          : optional comma
(?=.*\1)    : positive lookahead, check if thhere is the same word (contained in group 1) somewhere after

Given an input like: dangerous,dangerous,hazardous,perilous,dangerous,dangerous,hazardous,perilous

We got:

dangerous,hazardous,perilous
🌐
Regex Tester
regextester.com › 93564
Remove duplicate phrases - Regex Tester/Debugger
Regex Tester is a tool to learn, build, & test Regular Expressions (RegEx / RegExp).
🌐
GeeksforGeeks
geeksforgeeks.org › python-remove-duplicates-words-given-sentence
Python | Remove all duplicates words from a given sentence - GeeksforGeeks
The unique words are joined back into a string with ' '.join(res), resulting in s2 = "Geeks for". In this method we use dictionaries. In Python 3.7 and later dictionaries remember the order in which items are added. By using dict.fromkeys() we can remove duplicates while keeping the order of the words intact.
Published   December 30, 2024
🌐
Regular-Expressions.info
regular-expressions.info › duplicatelines.html
Regexp Example: Deleting Duplicate Lines or Items with Regular Expressions
Simply open the file in your favorite text editor, and do a search-and-replace searching for ^(.*)(\R\1)+$ and replacing with \1 or $1. For this to work, the anchors need to match before and after line breaks (and not just at the start and the end of the file or string), and the dot must not ...
🌐
LinuxQuestions.org
linuxquestions.org › questions › linux-newbie-8 › regex-remove-duplicate-words-how-4175655508
[SOLVED] RegEx remove duplicate words - How?
Hello I want to remove repetitive duplicate words in a text. Like in the following example 'The the'. You´re Editing a document and would like
🌐
Quora
quora.com › In-Python-how-could-you-remove-consecutive-duplicate-words-from-a-string-while-preserving-everything-else-like-newlines-tab-spaces-other-words-punctuations-etc
In Python, how could you remove *consecutive* duplicate words from a string, while preserving everything else like newlines, tab, spaces, other words, punctuations, etc? - Quora
Answer (1 of 4): The most direct way to do this, if maybe a bit clumsy and verbose, is probably: * Iterate the string, extracting (word, startpos, endpos) tuples. Or regex match objects, if you know how to do that. The start and end should include the extra non-word characters around the words,...
🌐
w3resource
w3resource.com › python-exercises › string › python-data-type-string-exercise-90.php
Python: Remove duplicate words from a given string - w3resource
Write a Python program to use collections.OrderedDict to filter out duplicate words and output the resulting string. ... Previous: Write a Python program to remove unwanted characters from a given string.