c# - Regular Expression for exact match of either 4 integers or 2 doubles in a line -


i trying identify lines in file have either 4 integer or 2 double values. regular expression below:

 var match = new regex(@"^(?<values>(((\d+\s*){4})|(\d+\.\d+\s*){2}))$"); 

sample of lines in file getting parsed:

element 1 2 8 24 2 1 1 0 1 129 2 2 0 0  30.200001 1000.0000 208 0 0 0 0 0 0 0  ..... ..... 

here, regular expression matches correctly above lines no 4 & 5. that's ok. but, it's matching line no 3 (0 1 129). that's problem me. kindly suggest:

  1. why regular expression matching line no 3.
  2. correct regular expression matches either 4 no. of integers or 2 no. of double values in line.

i think you're looking for:

^(((\d+\s+){3}\d+)|(\d+\.\d*\s+\d+\.\d*))\s*$ 

tested here.


explanations

^(   ((\d+\s+){3}\d+) # 4 numbers separated @ least 1 space   |   (\d+\.\d*\s+\d+\.\d*) # 2 floats separated @ least 1 space )\s*$ # optional spaces @ end of line (e.g., line 4) 

the error in initial attempt lack of mandatory space between numbers.


Comments

Popular posts from this blog

Qt QGraphicsScene is not accessable from QGraphicsView (on Qt 5.6.1) -

php - Cannot override Laravel Spark authentication with own implementation -

What is happening when Matlab is starting a "parallel pool"? -