Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,700 questions

55,459 answers

573 users

How to remove duplicate words with Unicode characters from free‑text in Ruby

1 Answer

0 votes
require 'set'

# Removes duplicate words from a free-text string containing Unicode characters.
# Preserves word order and the case of the first occurrence.
#
# @param input [String] The input string containing text and punctuation.
# @return [String] Space-separated unique words.
def remove_duplicate_words(input)
  return '' if input.nil? || input.strip.empty?

  # \p{L}+ matches sequences of any Unicode letter (Latin, Japanese, Greek, Cyrillic, etc.)
  # \p{N}+ matches digits if needed: /[\p{L}\p{N}_]+/
  words = input.scan(/[\p{L}\p{N}_]+/)

  # Set for O(1) case-insensitive duplicate tracking
  seen_words = Set.new

  # Filter words sequentially while keeping the first occurrence's original case
  unique_words = words.select do |word|
    # Set#add? returns nil if the lowercased word was already present
    seen_words.add?(word.downcase)
  end

  # Join unique words with a single space
  unique_words.join(' ')
end

# Main
input = "Hello! こんにちは,  ,hello こんにちは Bună ziua; Γεια σας Bună ziua *HELLO* Γεια σας"

result = remove_duplicate_words(input)

puts result



# run:
#
# Hello こんにちは Bună ziua Γεια σας
#

 



answered Aug 4 by avibootz

Related questions

...