Bill McCarthy wrote:
On Sat 5-Aug-06 10:42pm -0600, A.J.Mechelynck wrote:

Bill McCarthy wrote:

Example 1:

    :echo "<" . matchstr("  1.2345 ","[0-9.]") . ">"<CR>
    <1>

Example 2:
    :echo "<" . matchstr("  1.2345 ","[0-9.]*") . ">"<CR>
    <>

Why isn't the second exampe returning <1.2345>?

Is there a better way of stripping spaces off a string?

What you get is the first (leftmost) substring matching the pattern.

In the first case the pattern matches exactly one dot or digit, and it
matches the 1 at position 2.

In the second case the pattern matches zero or more dots and digits, and
it matches the null string at position 0.

That makes sense.

If you had specified \+ as multi instead of * you would (IIUC) have got
what you wanted.

I had:

Example 3:

    :echo "<" . matchstr("  1.2345 ","[0-9.]\+") . ">"<CR>
    <>

Example 4:

    :echo "<" . matchstr("  1.2345 ","\s*\zs[0-9.]\+") . ">"<CR>
    <>

Why did both of those fail?

When giving a double-quoted string to a function as an argument, backslashes are interpreted before the function receives the argument. Use single quotes to pass the argument literally; or if you want double quotes, then double the backslashes.

        :echo "<" . matchstr("  1.2345   ",'[0-9.]\+') . ">"
<1.2345>

See the differences between the two kinds of quotes, starting at ":help expr-string" (where first double-quoted strings, then single-quoted strings, are discussed).


To "strip spaces off a string" I would have used substitute(string, " ",
"", g)

That's much better:

    :echo "<".substitute("  1.2345 "," ","","g").">"<CR>
    <1.2345>

Thanks Tony!


My pleasure.


Best regards,
Tony.

Reply via email to