aspose file tools*
The moose likes Java in General and the fly likes String replaceAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String replaceAll()" Watch "String replaceAll()" New topic
Author

String replaceAll()

vivek ja
Ranch Hand

Joined: Feb 24, 2005
Posts: 80
I am using the following code to replace String
str = str.replaceAll("<?xml version = '1.0'?>","");
The str i get after running this has the <?xml version = '1.0'?> not replaced.

But if give some simple string like
str = str.replaceAll("xml",""); it works. Here the xml is replaced by blank.
Why is this happening? How do i get it working, is there any work around?

Thank you!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

The first parameter of the replaceAll() method is a regex -- not just a straight string. You need to give it a valid regex that represents the pattern you are replacing.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
vivek ja
Ranch Hand

Joined: Feb 24, 2005
Posts: 80
How do i find the regex for this particular string.
I found the Class Pattern in Sun's site that lists the regex

But when I replace space with \s I am getting a compilation error.
It would be really helpful if you can you show me an example how to convert a string to regex?
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
try \\s
[ February 28, 2005: Message edited by: Max Habibi ]

Java Regular Expressions
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

Originally posted by vivek ja:
How do i find the regex for this particular string.
I found the Class Pattern in Sun's site that lists the regex

But when I replace space with \s I am getting a compilation error.
It would be really helpful if you can you show me an example how to convert a string to regex?


This is one of the reasons that I don't like the Java regex library. You have to deal with *both* the regex library and Java. "\" has special meaning in a Java string to the compiler, so to get a "\" for the regex string, you need another "\".

Henry
vivek ja
Ranch Hand

Joined: Feb 24, 2005
Posts: 80
I got it finally!
The final regex looks like this \\<\\?xml\\sversion\\s=\\s'1.0'\\?\\>

Thanks guys!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: String replaceAll()
 
Similar Threads
why javaw file io dose not work properly
replace String input with parenthesis
Regex for adding CDATA to XML nodes
how can i parse?
String input with parenthesis