Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Regex to replace beginning of line whitespace

807591Apr 15 2008 — edited Apr 16 2008
Hi,

I'm trying to figure out a regex to use in java that would replace each space character at the beginning of the line with a  . I basically want to preserve indenting that someone has done with space characters in an input field.

I'm currently trying:

s.replaceAll("(?<!\\S+) ", "\\&nbsp;")

which works well enough, but will also replace space characters that occur later in the line. I'm curious if there's an approach that will allow a match on ^\\s+ and then allow me to replace each individual space character with a &nbsp;. I basically don't know how to get the count of the number of space characters that matched the regex and then use that in the replace string, if it's possible at all.

Here's an example:

1. hello world
a. good bye
2. hello world
a. good bye
b. good bye

becomes

1. hello world
&nbsp;&nbsp;&nbsp;a. good bye
2. hello world
&nbsp;&nbsp;&nbsp;a. good bye
&nbsp;&nbsp;&nbsp;b. good bye


Thanks,
Don
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 14 2008
Added on Apr 15 2008
21 comments
1,012 views