4

If I want to get the length of each match within the parentheses in the following regex, how do I do it?:

^\(\-\+\s\)\+

I'm trying to modify the width of columns in a buffer with data that is laid out as a table. Since the first two rows of the table will look like this

 DESIGN_ID DESIGN_YEAR SOURCE_REFERENCE
---------- ----------- ----------------

I want to use the regular expression to find the current width of each column.

CC BY-SA 2.5
1

1 Answer 1

6

Well, how do you want to capture it?

This will put it at the beginning of all the matching lines:

:%s/^-\+\%(\s-\+\)*\s\?$/\=strlen(submatch(0)) . ': '. submatch(0)

\= lets you substitute the result of a vimscript expression for a matching string. submatch(0) is the string matched (submatch(n) would be the nth group).

CC BY-SA 2.5
3
  • with very magic: :%s/\v^-+%(\s-+)*\s?$/\=strlen(submatch(0)) . ': '. submatch(0) Jun 25, 2011 at 11:39
  • instead of using + and \? here, I'd suggest using \{1,} and \{-}, because both gives you a bit more flexibility and makes it easier to change around. [pattern]\{n,m} means match where pattern between n and m times. [pattern]\{n,-} the '-' operator makes it non-greedy May 13, 2012 at 5:19
  • The relevant help page for this can be found under sub-replace-expression.
    – timss
    Mar 11, 2016 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.