I am trying to convert a String '1'
to a Number (int) 1
in a vimL script. I have used the built-in command str2nr()
so far, however I was not able to write this in an elegant and effective way.
Ideally I would like to catch invalid strings before attempting to convert them to an integer.
For example:
'abc1'
will return 0
when run through the str2nr()
command.
I probably need the right regex pattern to catch anything such as:
'a'
, 'a1b'
'7xy'
as an illegal value and anything like: '1'
or '7'
as a legal value, thus filtering out all non-integer values.
I tried something in the lines of:
let l:value = 'abcX1'
let l:debug = l:value =~ '\[0-9]^\[A-Z]\^[a-z]\' ? "YES" : "NO"
echom l:debug
This is expected to return a NO
, while this:
let l:value = '7'
let l:debug = l:value =~ '\[0-9]^\[A-Z]\^[a-z]\' ? "YES" : "NO"
echom l:debug
is expected to return a YES
.
However, as I said, I am not good with regular expressions and probably building the wrong pattern up in those examples above as they are not working.
Thanks.
\D
like this:let debug = value =~ '\D' ? "NO" : "YES"
(Also:help /character-classes
might help you)let l:debug = empty(a:value =~ '[^0-9]') ? "YES" : "NO"
'[^0-9]'
is the correct answer to this -- it will match any string with any characters besides those. You should write that as an answer as well, @symbolix.