How to match the last word in a sentence?
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.
"John Doe Jr".replaceAll("(\\S+)$", "<strong>$1</strong>")
\S is a non-whitespace character
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.
精彩评论