tags:

views:

46

answers:

2

I want to transform in Java:

dd fdas dd fdas fads f das fdasf + - || dasf
into:
"dd" "fdas" "dd" "fdas" "fads" "f" "das" "fdasf" + - || "dasf"

basically I want to add quotes around words. \w* -> "\w*\"

+4  A: 

replaceAll can do this:

String result = input.replaceAll("(\w+)", "\"$1\"");
Konrad Rudolph
You should group the word to use it in the replace
Colin Hebert
@Colin: thanks, slipped my mind.
Konrad Rudolph
@Colin, Konrad You could use `$0` if you're not grouping it. So `replaceAll("\w+", "\"$0\"")` <- this works in .Net - I don't know for sure that the syntax is equivalent in Java.
lasseespeholt
@lasse: That should work too. I prefer explicit grouping, though.
Konrad Rudolph
I though I won't get grouping in replaceAll. +1 for Java
Gadolin
A: 

It's fairly simple. Use preg_replace and sorround all text captures with quotes.

preg_replace("/([a-z0-9]+)/i", '"$1"', $string);

You will have to find the replacement of preg_replace for java :)

flaab