• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regex and backslash  RSS feed

 
Rakesh Jayaramaiah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a regex code like this.
       
       /****************CODE****************/
        public class Main {


   public static void main(String[] args) {
   System.out.println(validateAddress("Test C\O good:product"));
   }
       
           public static boolean validateAddress(String address) {
return address.matches("^[a-zA-Z0-9~`!@#$%^&*()_+={|}:;'<,>? -/\"\t\n\\[\\] .]*$");
           }

        }

        /**********************************/

When i run this i get false as my expression does not accept \ character. I tried to include the \ but failed.

Can you please help as to how to include the \ character in my regex for validation ?



Thanks,
Rakesh



 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In regex, the backslash has a special meaning, so to get a literal backslash, you will need to escape it with another backslash. Hence, you will need "\\" instead of "\".

With Java literal strings, the backslash has special meaning, so to get a literal backslash, you will need to escape it with another backslash. Hence, you will need "\\\\" instead of "\\".

In your example, your caller literal string needs to be escaped (2 backslashes), and your regex needs to be escaped (4 backslashes).

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!