• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Regex problem

 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This works
 
reply
    Bookmark Topic Watch Topic
  • New Topic