2

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?

1
  • You want to use only replaceAll()? Commented Dec 10, 2013 at 5:33

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer +1 used regex
@JqueryLearner note that the other answer also uses regexes, the fact that doesn't use complex wildcards and other regex patterns does not mean is not a regex at all.
3

Play tricky on comma, and be faster:

"M,L,XL,XXL".replaceAll("M", "size M").replaceAll(",",",size ")

6 Comments

@JqueryLearner but this is a faster and simpler solution.
@LuiggiMendoza yes I agree +1 from my side but this is not exactly as per OP
@JqueryLearner sometimes you want to use a flamethrower when you only need some matches...
@JqueryLearner of course it does. This is the first result I got when searching regex performance: codinghorror.com/blog/2006/01/regex-performance.html
|
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.