regex - Regular expression matching a numerical string exactly -


i have string looks 600/-4.412/11 , 1 looks 600/11

[optional sign][float or integer]/[optional sign][float or integer]/[optional sign][float or integer] [optional sign][float or integer]/[optional sign][float or integer] 

example:

1) 600/-4.412/11 2) 600/11 

and need find regular expression matches 1 , 1 matches 2. both expressions mustn't select/match other one. humble regex knowledge managed build expression:

([-+]?[0-9]+(\.?[0-9]+)?\/?){3} 

the problem expression matches 1) 2) according http://gskinner.com/regexr/. can fix or @ least tell me why happening since hoped had change {3} {2} in order different matching.

problem

the problem regex allows repeated subpattern, i.e. [-+]?[0-9]+(\.?[0-9]+)?\/? match without restricting each section of numbers delimited /.

for example in question: 600/11, first repetition match 600/, second 1 , third 1 last 1.

solution 1

wrong attempt

for validation, can change make works want:

^([-+]?[0-9]+(\.[0-9]+)?(?:/|$)){3}$ 

(?:/|$) forces number (floating point or integer) end /, or end of string. make sure each repetition not match within same number.

^ added in front , $ behind make sure string has 3 numbers.

the text not crossed out still applies in correct solution.

the correct solution

however, above regex wrong. still allow invalid input such 1/2/3/ match (ends /). need add assertion @ end prevent case above matching:

^([-+]?[0-9]+(\.[0-9]+)?(?:/|$)){3}(?<!/)$ 

(?<!/) zero-width negative look-behind checks character before end of string not /.

solution 2

it less buggy write regex in form [number]([delimiter][number]){repeat} in such cases, rather fiddling form ([number][delimiter/ending]){repeat}.

the answer below strictly validates input:

^[-+]?[0-9]+(\.[0-9]+)?(?:/[-+]?[0-9]+(\.[0-9]+)?){2}$ 

the above matching case of 3 numbers. change 2 1 (or remove {2}) match 2 numbers.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -