开发者

Value pass to regular expression should have specified character

开发者 https://www.devze.com 2023-02-20 00:17 出处:网络
I am trying to create validation so the value passed should be in format as i expect. For example values can be 40% or 40GB.

I am trying to create validation so the value passed should be in format as i expect.

For example values can be 40% or 40GB.

I am trying to use开发者_JAVA百科 the regex

(\\d*\\.?\\d*)([MB|GB|TB|PB|%]?)

Is above regex correct?


No it's wrong.

  1. The character class [xyz] is for matching single character. In fact, [MB|GB|TB|PB|%] means matching a single character which is one of M, B, |, G, T, P or %. Grouping should be done with (?:...) not [...].

    ((?:MB|GB|TB|PB|%)?)
    

    Of course it is better to collect the prefixes of the bytes. Also, I think the unit is mandatory, so the ? should be removed:

    ([MGTP]B|%)
    
  2. The regex matches an empty substring, so anything would pass, e.g. use

    \d+(?:\.\d+)?
    

    instead.

Together:

(\d+(?:\.\d+)?)([MGTP]B|%)


try this

^\d*([MGTP]B|%)$

DEMO

0

精彩评论

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

关注公众号