0

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 the regex

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

Is above regex correct?

2
  • How about actually testing strings with your regex? Commented Mar 28, 2011 at 7:43
  • 1
    what is your target language? Commented Mar 28, 2011 at 7:45

2 Answers 2

1

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|%) 
Sign up to request clarification or add additional context in comments.

3 Comments

@Developer: No, you need (\d+(?:\.\d+)?)([MGTP]?B|%) for 40B (and it matches the possibly invalid 4.5B.)
@Developer: In that case the whole unit is optional (\d+(?:\.\d+)?)([MGTP]?B|%)?. You know what ? means right?
@Developer: This is getting ridiculous, how is 'AS' a unit of storage size? ((\d+(?:\.\d+)?)([MGTP]?B|%|AS)?, and please do learn regex properly. All the above requests can be solved by simply adding more alternations. I will stop answering comments here for the same pattern.)
1

try this

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

DEMO

1 Comment

@Kenny, Thanks for the optimized way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.