Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regular Expression Question

 
Tafta Zani
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I have search the forum about regular expression and i have read the Java API too but i haven't found any solution for my problem.

I have a string formated as LLVAR. The rule is the first two 'L's are numeric character represent the length of the string contained in the VAR.

eg: 05ABCDE
LL=05
VAR=ABCDE

what kind of regular expression will be suitable for validating such rule.
I need to validate that the first two characters are numeric and the following string has the length of the integer value of the first two 'L'

Thank you,
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't use regular expressions for this. But it shouldn't take more than a single line of code to validate this without regexps. Consider this for starters:



Can you fill in the missing expression, and then put it into a single expression? Don't forget to handle the exception that Integer.parseInt can throw.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Ulf,
if i do something like this

 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That doesn't check whether the remainder of the string is as long as the first two digits prescribe. In this case it's easier not to use regexps.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya that i know,
its just the first validation which should be done. and my point is if the string itself is invalid like the first two characters are not integers, then we need to catch the NumberFormatException and throw the error,
i think this approach is better than the catching the exception.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by gaurav abbi:
then we need to catch the NumberFormatException and throw the error


Well, if you want to throw an exception if the validation doesn't work out, then don't catch NumberFormatException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic