2

I want to replace the following strings:

chrome, internet explorer, mozlla, opera

or

john, jack, jill, bill

with

?, ?, ?, ?

I need a regular expression for Java which can replace the above string. Find all words and replace with question marks

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arun
  • 3,036
  • 3
  • 35
  • 57
  • Are you saying you want to replace words "chrome", "internet explorer", "mozlla", and "opera" with question marks? – ngen Jun 12 '11 at 07:00
  • sorry, edited the question. Please see – Arun Jun 12 '11 at 07:07
  • You want to transform a comma- and space-separated list of words into a comma- and space-separated list of question marks? What happens with the list `pink, green, sky blue, yellow`? Does it become `?, ?, ?, ?` or `?, ?, ? ?, ?`? – Ted Hopp Jun 12 '11 at 07:12
  • Thanks Ted, got my answer below. – Arun Jun 12 '11 at 07:15

1 Answers1

4

Something like this:

String output = myString.replaceAll("(chrome|internet|explorer|mozlla|opera)", "?");

[Edit] You are changing the question faster then I can answer.

To replace any word:

String output = myString.replaceAll("\b(\w+)\b", "?");

\b - first or last character in the word
\w - alphanumeric
+ - one or more repetitions

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
  • Sorry, I didn't explain properly. I need a generic replace. Edited the question. Please see – Arun Jun 12 '11 at 07:10
  • THANK YOU so much. It works. Can you explain that please... :) – Arun Jun 12 '11 at 07:12
  • I was trying ,[.*], - I thought this should have worked for words in between commas at least. I just ordered the book Regular Expressions Cookbook. – Arun Jun 12 '11 at 07:14