Reman
Reman

Reputation: 8119

Submatches in string

I'm trying to find the longest number of decimals in a string.

p.e. string:

(3+2,44)*2,134 + (2,1 + 2,91280)*1,2

search:

,\zs\d\+

answer = 5 (,91280)

I know that there is a way to find submatches in a document using the substitute command but how do I find submatches in a string?

Upvotes: 0

Views: 71

Answers (1)

glts
glts

Reputation: 22734

To get just the length of the longest sequence of decimal digits, you can combine a couple of standard functions like this:

:echo max(map(split(str, '\D\+'), 'strlen(v:val)'))

When str is the string '(3+2,44)*2,134 + (2,1 + 2,91280)*1,2' this echoes 5.

To fetch the (first) longest match itself you could refine the expression further:

:echo matchstr(str, '\d\{' . max(map(split(str, '\D\+'), 'strlen(v:val)')) . '}')

Or simply :echo max(split(str, '\D\+')) does work, too.

See :h function-list for a lot more useful functions.

Upvotes: 2

Related Questions