Indigenuity
Indigenuity

Reputation: 9740

Using regular expressions to grab initial letters of string while preserving punctuation and white space

Take the following Java string:

"Hello, World"

I want to take that string and turn it into:

"H, W"

There are java utilities that will turn it into "HW", but I want to preserve the white space and punctuation. I can do this by splitting the string and processing each word individually, but that is too slow. I'm trying to find a regular expression where I can grab all letters of a word but the first? I.e, grab "ello" and "orld" and replace them with "". I know that "\w" will grab all letters, but is there a way to exclude the first letters of each word?

Upvotes: 4

Views: 178

Answers (1)

Mark Elliot
Mark Elliot

Reputation: 77064

The capture sequence would look something like:

(\\w)\\w*

And the replace like:

$1

The idea is you want to capture the first character as its own group, and simply consume as many extra word characters as possible.

Upvotes: 3

Related Questions