This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clarification on Regular Expression

 
P Bala
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have the follow regex pattern as
private Pattern pattern = Pattern.compile("^[a-zA-Z_0-9 -@#$]*$");

when i tried matching this pattern to a string "test@test#asd$!com", it passes when i expected to fail.

Could anyone please help me undersand.
 
Henry Wong
author
Marshal
Pie
Posts: 21207
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when i tried matching this pattern to a string "test@test#asd$!com", it passes when i expected to fail.


The issue is the "[a-zA-Z_0-9 -@#$]" part of the pattern. You are trying to match... a to z, A to Z, the underscore, 0 to 9, space to @ sign, the hash, and the dollar sign.

I am assuming that the reason you "expected [it] to fail" is because you believe that the "!" character is not on that list. Unfortunately, it is. It is in the "space to @ sign" range.

Henry
[ December 20, 2007: Message edited by: Henry Wong ]
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FYI - that's a MUCH harder expression then you'll find on the real exam!
 
P Bala
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh... Thanks Henry. I was wanting to include space, dash(-),@,#,$ signs. I want to exclude !,^, (),<>,;,:,* and words like (SELECT),(TABLE). I seek help in framing such a regular expression.

I sincerely thank you in advance.
 
Henry Wong
author
Marshal
Pie
Posts: 21207
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by P Bala:
Oh... Thanks Henry. I was wanting to include space, dash(-),@,#,$ signs. I want to exclude !,^, (),<>,;,:,* and words like (SELECT),(TABLE). I seek help in framing such a regular expression.

I sincerely thank you in advance.


If you want the dash as a literal character, and not as a range designator, then you have two choices. You can escape it with a backslash. Or you can make it the first or the last character between the square brackets -- as it can't be a range designator when there isn't a range.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic