I want to transform this string
M,L,XL,XXL
to
size M,size L,size XL,size XXL
using replaceAll() method. Is it possible?
You can do this using a Positive Lookahead.
String s = "M,L,XL,XXL";
s = s.replaceAll("(?=(\\w+))\\b", "size ");
System.out.println(s); // size M,size L,size XL,size XXL
See Live demo
Regular expression:
(?= look ahead to see if there is:
( group and capture to \1:
\w+ word characters (a-z, A-Z, 0-9, _) (1 or more times)
) end of \1
) end of look-ahead
\b the boundary between a word char (\w) and not a word char
Play tricky on comma, and be faster:
"M,L,XL,XXL".replaceAll("M", "size M").replaceAll(",",",size ")
I would propose the following:
"M,L,XL,XXL".replaceAll("((?:\\w+)(?:,|$))","size $1")
as shown in http://fiddle.re/zrq88. The $1 is a "backreference", referring to the first "capture group". A capture group is any text matched by an expression in parentheses, with some exceptions (e.g. when the left parenthesis is followed by ?:).
See http://www.regular-expressions.info/backref.html for more information.
replaceAll()?