This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread 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 Murach's Java Servlets and JSP this week in the Servlets 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: 30050
    
149

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: 18492
    
  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: 30050
    
149

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.
 
wood burning stoves
 
subject: regular expression with special character
 
Similar Threads
Regular expression
Operators and Precedence
I don't think I understand how Regular Expression works!
Validating The Date String
Regular Expressions: A String should not contain the word "TEST"