g.t.w.d
g.t.w.d

Reputation: 621

Regex to match a doubles separated by one space only

I am trying to check a match as the user enters values in the text box.

Valid values for the textbox are like this:

"-"

"-5.5"

"-5.5 6.5 7.5"

Invalid would be

"-5.5   6.5    "

Edit: ^there is more than one space between -5.5 and 6.5, but it doesn't show for some reason.

"3.5 "

^(-?)(\d+\.?\d?)\s?(-?\d+\.?\d?)

Keep in mind that the negative sign is the only special character, other than the decimal point, allowed in here.

Thanks.

Upvotes: 1

Views: 651

Answers (3)

p.s.w.g
p.s.w.g

Reputation: 149030

I think this is what you're looking for:

^(-|-?\d+\.?\d?([ ]-?\d+\.?\d?)*)$

This will match either a single hyphen or any number of space-separated positive or negative numbers with an optional decimal point and at most one digit after it. This will allow values like "5.5 6.5" or "-5.5 -6.5" (your question didn't specify if it should match those or not)

You can test it here.


Update

This will allow many more matches, but satisfies the new requirement of supporting every valid sequence as the user is typing. Of course, it allows even more, since it's impossible to determine the difference between invalid input and input which is merely incomplete (e.g. -5 -).

^(-?(\d+\.?\d?( |$)|$))*$

You can test it here.

Upvotes: 2

unlimit
unlimit

Reputation: 3752

You can try this:

^(-(\d+\.\d+)*([ ]\d+\.\d+)*)$

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213281

You can use this:

^-(?:\d+[.]\d+(?:[ ]\d+[.]\d+)*)?$

Explanation:

^   
  -                   // Match '-'
  (?:                 // An optional non-capturing group
      \d+[.]\d+       // Match pattern - 14.45
      (?:             // A 0 or more times repeating Non-capture group
         [ ]          // A space
         \d+[.]\d+    // Pattern matching - 14.56
      )*              
  )?    
$    

Upvotes: 4

Related Questions