• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regular expression - matching on full stop

 
Sharon Hour
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to match a literal full stop in regular expression. Expression is

if(Pattern.matches("[0-9]{2}\.{1}[0-9]{2,4}", freq))

I want to match 2 numbers followed by a full stop followed by 2-4 more numbers. However when i compile am getting error : illegal escape character and its pointing to the full stop?

Any help appreciated, this is my first time using regular expressions in java, but was following api documentation and thought above was correct!
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that '\' escapes characters in Strings. So (even though your expression looks like a valid expression) you need to escape the escape character, so to speak. Try '\\.'
 
Sharon Hour
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great that worked- thanks! But i dont fully understand why. Is it because the regular expression is being defined in a string. If it wasn't in a string would a single backslash have worked?

Thanks,
Sharon
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If it wasn't in a string would a single backslash have worked?

I don't know how else you could describe a regular expression except in a String.

It works this way because somewhere in the Java API some piece of code is going through any string defined and looking for '\' because it is special. Remember that:

is a String containing the character ", whereas:

is a compiler error.

[ September 13, 2004: Message edited by: Paul Sturrock ]
[ September 13, 2004: Message edited by: Paul Sturrock ]
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Sturrock:
I don't know how else you could describe a regular expression except in a String.


They could be read in from a file or the command line, or typed into a textfield (e.g., in a search/replace dialog). In any of those cases, a single backslash would suffice.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic