Vim脚本中按字符串内数字及后缀字符排序数组的自定义函数求助
Custom Natural Sort Function for Vimscript
Got it, let's fix this natural sorting issue you're having! The built-in sort(arr, 'n') doesn't work here because it tries to parse the entire string as a single number—your elements are a mix of text, numbers, and optional suffixes, so we need a custom comparator that breaks down each element properly.
Here's the my_sort function you need, along with a breakdown of how it works:
function! my_sort(a, b) " Extract numeric portion and convert to integer for proper number comparison let num_a = matchstr(a:a, '\d\+') + 0 let num_b = matchstr(a:b, '\d\+') + 0 " First compare by numeric value if num_a != num_b return num_a - num_b endif " If numbers are equal, compare the full strings lexicographically " This handles suffixes like A/B after the same number return a:a > a:b ? 1 : -1 endfunction
How it works:
- Extract numbers:
matchstr(a:a, '\d\+')grabs all consecutive digits from each element. Adding+ 0converts that string to an integer, so we get proper numeric comparison (no more "10" being treated as smaller than "8" like string comparison would do). - Primary sort by number: If the numeric parts are different, we return their difference—this ensures smaller numbers come first.
- Secondary sort by suffix: When two elements have the same number (like "FUNC10A" and "FUNC10B"), we fall back to lexicographical comparison of the full strings, which puts "A" before "B" as expected.
Usage example:
let arr = ["FUNC10B", "FUNC8", "FUNC2", "FUNC10A"] call sort(arr, 'my_sort') echo arr " Output: ['FUNC2', 'FUNC8', 'FUNC10A', 'FUNC10B']
This function is also flexible if your prefixes ever change (e.g., if you have "PROC3" or "TEST10X")—it only cares about the numeric segment and whatever comes after it, so it'll still sort correctly.
内容的提问来源于stack exchange,提问作者Avi
相关产品推荐
相关产品推荐

