• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regex problem

 
Carl Pettersson
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Carl Pettersson
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This works
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic