Mawia
Mawia

Reputation: 4310

Regex on replaceAll()

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?

Upvotes: 2

Views: 161

Answers (3)

hwnd
hwnd

Reputation: 70750

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

Upvotes: 5

Peter Alfvin
Peter Alfvin

Reputation: 29449

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.

Upvotes: 2

user987339
user987339

Reputation: 10727

Play tricky on comma, and be faster:

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

Upvotes: 3

Related Questions