How to test if a gawk string contain a number?

Posted by Tim Menzies on Stack Overflow See other posts from Stack Overflow or by Tim Menzies
Published on 2012-10-12T15:35:22Z Indexed on 2012/10/12 15:36 UTC
Read the original article Hit count: 328

Filed under:

In I know two ways to test if a string contains a number. Which is best?

Method one: using regular expressions:

function method1(x) {
    return x ~ /^[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][+-]?[0-9]+)?$/
}

Method two: the coercion trick (simpler):

 function method2(x) {
     return (x != "") && (x+0 == x)
 }

Is there any reason to favor the more complex method1 over the simpler method2?

© Stack Overflow or respective owner

Related posts about gawk