tags:

views:

84

answers:

2

Suppose we have one sentence (several words without a dot after the last one).

I need to wrap the last word with some html tags (for example, <strong>lastword</strong>).

How can I achieve this with java regular expressions?

I've already tried this:

"John Doe Jr".replaceAll ("( .+$)", "<strong>$1</strong>");

but it results in

John<strong> Doe Jr</strong>

p.s. It's ok if we have a whitespace after <strong>, the main problem is that the pattern matches the biggest subsequence while I need the smallest one.

+2  A: 

The last word would be the non-space characters preceding the end or the string. You can define a set of characters with [] and negate that with a ^, as in [^a-z] to match everything but a-z.

"John Doe Jr".replaceAll("([^ ]+)$", "<strong>$1</strong>");

This also has the advantage that it doesn't require that there be any spaces in the string, unlike Marcelo Cantos' answer.

Ezku
+2  A: 
"John Doe Jr".replaceAll("(\\S+)$", "<strong>$1</strong>")

\S is a non-whitespace character

Vitalii Fedorenko
`\\S is not a space operator` is bad wording. The official definition is: `A non-whitespace character: [^\s]` (see here: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html )
seanizer
@seanizer fixed
Vitalii Fedorenko