File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Escaping special characters regex/function help 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 "Escaping special characters regex/function help" Watch "Escaping special characters regex/function help" New topic

Escaping special characters regex/function help

Sean Chang

Joined: Feb 12, 2009
Posts: 12
Hey all,

I needed a little help writing a function in java that does the follow for espacing, I want to use regular expressions, I need the following characters to be replaced by a “~”

The special characters are replaced as follows:

1. Newline, backspace, Control-M, carriage return, vertical tab characters are each replaced with "~"

2. Double quotes (") are replaced with single quotes (')

3. Then single quotes are escaped by inserting a backslash before each one.

Can someone give me a hand writing this? I don’t know regular expressions so it’s difficult for me to get going on this.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37890
A good place to learn regular expressions is in the Java™ Tutorials.
Henry Wong

Joined: Sep 28, 2004
Posts: 18498

I don’t know regular expressions so it’s difficult for me to get going on this.

I am a big believer that you should never use code that you don't understand. So, if you don't know regex, then you probably shouldn't use it.

Take a look at the string replace() methods. It will do what you want, and you don't need to know regex.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
It is sorta covered in the JavaRanch Style Guide.
subject: Escaping special characters regex/function help
Similar Threads
Regex help, replacing/espacing characters
String replace
Escape single quotes
how to read a file in a string
Generating Regular Expression at run-time