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 / General / March 2005

Tip: Looking for answers? Try searching our database.

stuck in regex

Thread view: 
<- Chameleon -> - 19 Mar 2005 19:25 GMT
I want to replace all
\   with    \\        and all
"   with    \"
in a String.

I use this line of code:
text = text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");

But i have PatternSyntaxException
Why?
HK - 19 Mar 2005 22:36 GMT
> I use this line of code:
> text = text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
>
> But i have PatternSyntaxException

"\\" results in a 1 character string containing a backslash
only. This is not a valid regular expression.

 Harald.
Kevin - 19 Mar 2005 23:06 GMT
I am also kind of stuck in the regex, I sometimes use this function to
do the string / substring replacement work.

 public String stringReplaceAllCaseSensitive (String orig, String
from, String to)
 {
    if ((from==null) || (from.length()==0))
     {
       println("\tWarning in stringReplaceAllCaseSensitive, from
string is empty. Ignored. ");
       return orig;
     };
     if (from.compareTo(to)==0)
       return orig;
    //
     int fromLength = from.length();
     //
     int start = orig.indexOf (from);
     if (start <0)
         return orig;
     //
     boolean greaterLength = (to.length() >= fromLength);

     StringBuffer buffer;
     // If the "to" parameter is longer than (or
     // as long as) "from", the final length will
     // be at least as large
     if (greaterLength)
     {
         buffer = new StringBuffer(orig.length());
     }
     else
     {
         buffer = new StringBuffer();
     };
     //
     char [] origChars = orig.toCharArray();
     int copyFrom=0;
     while (start != -1)
     {
         buffer.append (origChars, copyFrom, start-copyFrom);
         buffer.append (to);
         copyFrom=start+fromLength;
         start = orig.indexOf (from, copyFrom);
     }
     buffer.append (origChars, copyFrom, origChars.length-copyFrom);

     return buffer.toString();
 }
 //
HK - 19 Mar 2005 23:22 GMT
> I am also kind of stuck in the regex, I sometimes use this function to
> do the string / substring replacement work.
[quoted text clipped - 7 lines]
> string is empty. Ignored. ");
>         return orig;

Guess were this message ends up in a server application.
This should rather be either an IllegalArgumentException
or the docs should state that empty from is silently
ignored.

>       if (from.compareTo(to)==0)
>         return orig;
Why not from.equals(to) ?

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.
CharSequence,%20java.lang.CharSequence
)

 Harald.
Tony Morris - 19 Mar 2005 23:29 GMT
> I want to replace all
> \   with    \\        and all
[quoted text clipped - 6 lines]
> But i have PatternSyntaxException
> Why?

Here are a couple of tips.
A literal Java backslash looks like this: "\\"
A literal regex backslash looks like this: \\
Therefore, a literal regex backslash using Java looks like this: "\\\\"

Signature

Tony Morris
http://xdweb.net/~dibblego/

hiwa - 20 Mar 2005 02:12 GMT
> I want to replace all
> \   with    \\        and all
[quoted text clipped - 6 lines]
> But i have PatternSyntaxException
> Why?
Backslash requires special treatment BOTH in regex string
and Java String. See the example program:

public class ReplaceTest{
 public static void main(String[] args){
   String str = "\\he said \"I love you.\"\\";

   System.out.println("original: " + str);

   /* regex str for a single BS is \\, so the Java String for
      that is "\\\\" */
   str = str.replaceAll("\"", "\\\\\""); //dq -> BS + dq
   System.out.println("result1 : " + str);
   /* read the above comment for BS regex str */
   str = str.replaceAll("\\\\", "\\\\\\\\"); //BS -> double BSs
   System.out.println("result2 : " + str);
 }
}
hiwa - 20 Mar 2005 02:18 GMT
Oops!
Please reverse the calling order of my two replaceAll() calls.
Alan Moore - 20 Mar 2005 02:32 GMT
>I want to replace all
>\   with    \\        and all
[quoted text clipped - 6 lines]
>But i have PatternSyntaxException
>Why?

The arguments to replaceAll get processed twice: first by the
compiler, then by the Pattern (first argument) and Matcher (second
argument) classes, which do the actual matching and replacing.  Both
of those classes also treat the backslash as an escape character.  So,
to match a literal backslash character, or to insert one into the
replacement string, you have to double it, then double it again.  So
replacing a single backslash with a double backslash looks like this:

 text = text.replaceAll("\\\\", "\\\\\\\\");

The double-quote character, OTOH, has to be escaped for the compiler,
but it isn't special to the regex classes, so you only need one
backslash to escape it.  Of course, to add a backslash in front of it,
you have to use four of them, plus the one to escape the quote:

 text = text.replaceAll("\"", "\\\\\"");

Instead of doing in two passes, though, you can use the power of
regexes to do it in one:

 text = text.replaceAll("[\"\\\\]", "\\\\$0");

The regex, "[\"\\\\]", is a character class that matches either a
quote or a backslash, and the $0 in the second argument gets replaced
with whatever was matched by the regex.  For more info, check out this
site:

http://www.regular-expressions.info/
Aquila Deus - 20 Mar 2005 05:03 GMT
> I want to replace all
> \   with    \\        and all
[quoted text clipped - 6 lines]
> But i have PatternSyntaxException
> Why?

hmmmm... escape char nightmare, it happens in emacs too :-)


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.