开发者

Pattern matching a string

开发者 https://www.devze.com 2023-02-14 16:49 出处:网络
I need to validate that a string is of the following format/sequence LGaaaaaaaaaaYYMMDDnnnnn For the string to be valid, it has to start with the characters \"LG\" followed by 10 characters followe

I need to validate that a string is of the following format/sequence

LGaaaaaaaaaaYYMMDDnnnnn

For the string to be valid, it has to start with the characters "LG" followed by 10 characters followed by a date in the format (YYMMDD) following by 5 digits.

Here is what i have come up with

String patter = ^LG{1}[a-z][A-Z]{10}[0-9]{6}[0-9]{5}
  • How can i check that the string does start with "LG"
  • How do i check that ten characters after "LG" are indeed after the chara开发者_开发技巧cters "LG"
  • How do i check that YYMMDD is a valid date
  • How can i check that the digits at the end of the string are exactly 5 digits.

-- I could use Simpledateformat to validate the string as a date i think.

Thanks


It depends how you use it. If you use the Mather.matches method then the ^ is not really needed because it will match against the whole string. If you use find() method instead then the ^ will make a difference


  1. I think your regular expression should be more like: LG[a-zA-Z]{10}[0-9]{6}[0-9]{5}
  2. If the string matches the pattern, use substring to pull out the date and parse it with SimpleDateFormat to validate that it is truly a good date.
0

精彩评论

暂无评论...
验证码 换一张
取 消