This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes regular expression with special character Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "regular expression with special character" Watch "regular expression with special character" New topic
Author

regular expression with special character

Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30352
    
150

Does anyone know why these two code snippets output different things? The first outputs "tes" which is what I would expect. The second outputs "test" which implies the regular expression doesn't match.


According to the JavaDoc for the String class, these are supposed to be identical. Am I doing something wrong when transposing?

They both work correctly if I remove the $. Then both output "es".


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18745
    
  40

According to the JavaDoc for the String class, these are supposed to be identical. Am I doing something wrong when transposing?


You are calling the wrong method. You should be calling the replaceAll() method. The replace() method doesn't take a regex.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30352
    
150

Originally posted by Henry Wong:
You are calling the wrong method. You should be calling the replaceAll() method. The replace() method doesn't take a regex.

Henry,
A 3 minute response time. Very impressive!

And - doh! I thought "replaceAll". I even looked in the JavaDoc under "replaceAll" to see if it was defaulting to different pattern flags. I've used this method numerous times (correctly.) And yet staring at it - nothing.

Thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: regular expression with special character