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

Regex problem

Carl Pettersson
Ranch Hand

Joined: Sep 09, 2003
Posts: 73
I want to check if an string of digits is on the form of xxxxxx-xxxx, this should be done with an regular expression right? My problem is that I cannot seem to write an correct pattern. I read that in an pattern, the \d escape character is any digit 0 - 9, but I get an illegal escape character error... How is this done? I've tried

but it doesn't work when I type strNumber as "000000-0000"
/edit
Sorry, I had made an error in checking if that example string would work, so that works, but I want it to be able to be something else than 000000-0000
[ September 16, 2003: Message edited by: Carl Pettersson ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

If you literally type a Java string containing "\d", then the Java compiler tries to interpret \d as a Java escape sequence, like \n, which it's not. You have to escape the backslash -- i.e., use "\\d" -- so that the two characters \d get encoded into the string.
Although this is just basic Java, I think it's crazy that the Javadoc page for java.util.regex.Pattern doesn't mention this -- even just as a reminder.


[Jess in Action][AskingGoodQuestions]
Carl Pettersson
Ranch Hand

Joined: Sep 09, 2003
Posts: 73
Ok, thanks. Now the digits works, but it won't accept the dash. What sequence would that be? In the documentation, \p{punct} contains the dash sign, but it also says that it is only valid for US-ASCII, if I use it anyway, the program generates an PatternSyntaxException. Just writing it as - doesn't seem to work either
Jon Strayer
Ranch Hand

Joined: Dec 04, 2002
Posts: 133
This works


Jon
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regex problem