Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / February 2005

Tip: Looking for answers? Try searching our database.

unexpected regex replace

Thread view: 
Kiwi - 11 Jan 2005 09:36 GMT
Hello.

I tried the program below expecting an output like "To Phrase."

public class ToPhrase {
       public static void main(String[] args) {
               String s = "ToPhrase".replaceAll("(.)([A-Z])", "\1 \2");
               System.out.println(s);
       }
}

But the real output was broken. 2nd byte was 0x01 and 4th byte was 0x02.
Other bytes were normal ASCII characters.
What happened?

Thank you in advance.

Kiwi
Thomas Schodt - 11 Jan 2005 10:52 GMT
> I tried the program below expecting an output like "To Phrase."
>
[quoted text clipped - 8 lines]
> Other bytes were normal ASCII characters.
> What happened?

Two things.
The backslash character is a special character in Java, so you have to
escape it with a backslash, if you don't you end up using the octal
escape syntax.
In Java the "capturing group n" syntax can only be used in the pattern,
not in the replacement text (and remember to escape the backslash).

You can accomplish what you are trying to do
with look-behind / look-ahead

public class ToPhrase {
    public static void main(String[] args) {
        String s = "ToPhrase".replaceAll("(?<=.)(?=[A-Z])", " ");
        System.out.println(s);
    }
}
Kiwi - 13 Jan 2005 07:11 GMT
> The backslash character is a special character in Java

Thank you. I was stupid.

Kiwi
Thomas Schodt - 12 Feb 2005 21:52 GMT
> In Java the "capturing group n" syntax can only be used in the pattern,
> not in the replacement text (and remember to escape the backslash).

Correction.
<http://forum.java.sun.com/thread.jspa?threadID=595916>


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.