| Author |
Pattern Matching
|
Neh Agarwal
Greenhorn
Joined: Feb 27, 2009
Posts: 24
|
|
I need to validate product version entered by the user. The allowed pattern is any alphanumeric and a dot, i.e allowed values are:
1
1as.1dfd
11.11.hjh etc.
I am using the pattern as ^(\\w+.?\\w+)+$
The only problem with the ablove pattern is if the user gives only 1 digit or 1 letter, it fails to be matched
Can you please suggest a valid pattern.
Thanks, Please Help!
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
The only problem with the ablove pattern is if the user gives only 1 digit or 1 letter, it fails to be matched
The problem is caused by the fact that you have two word patterns (of one or more characters) -- making all words between the periods to be at least two or more characters.
You may want to make the optional period attached to a zero length look-ahead... Instead of this...
.?\\w+
try....
(\\.(?=\\w))?
And BTW, the period has special meaning in a regex -- you will need to escape it... which is what I did above.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
I haven't tested this, but you may want to try ^(?:\\w+\\.?)+$
John.
|
 |
Piet Verdriet
Ranch Hand
Joined: Feb 25, 2006
Posts: 266
|
|
John de Michele wrote:I haven't tested this, but you may want to try ^(?:\\w+\\.?)+$
John.
That will also match a String like: "abc.def." (ie. a String ending with a DOT, which is not desired, if I understand the OP correctly).
|
 |
Piet Verdriet
Ranch Hand
Joined: Feb 25, 2006
Posts: 266
|
|
Neh Agarwal wrote:I need to validate product version entered by the user. The allowed pattern is any alphanumeric and a dot, i.e allowed values are:
1
1as.1dfd
11.11.hjh etc.
I am using the pattern as ^(\\w+.?\\w+)+$
The only problem with the ablove pattern is if the user gives only 1 digit or 1 letter, it fails to be matched
Can you please suggest a valid pattern.
Thanks, Please Help!
Correct, that is because you used \\w+ twice, so, the minimum length of a String must be 2 to be matched.
Also note that the short-hand-character-class \w matches an underscore as well. If this is not what you want, you should use the following character class:
And the following regex will do the trick:
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Piet:
Oops! I think you're right. I forgot about the underscore and that pesky final dot.
John.
|
 |
Neh Agarwal
Greenhorn
Joined: Feb 27, 2009
Posts: 24
|
|
Thanks a lot, it works perfectly
|
 |
 |
|
|
subject: Pattern Matching
|
|
|