0

Currently I'm using:

\v(((^|,)[^,]*){3})(.*)

to match csv lines, the first part ((^|,)[^,]*){3} is to match 3 items, then the second part .* matches the rest.

However, if the csv line starts with a empty item, e.g. ,2,3,4,5, the regex will not match correctly, as ^ seems can be matched multiple times.

How could I avoid this, to make ^ matched only once?

Of course I can use:

\v(^[^,]*)((,[^,]*){2})(.*)

but then the matching items increased and other codes become more complex. I wonder if there is a "local" fix here.

1
  • Do you still have something open in your question? How can we help you further? Commented Oct 17 at 2:05

1 Answer 1

0

To match an empty line I would do:

^,*$

Basically matching a line that is full of ,.

Where:

  • ^ match the start of the line
  • $ match the end of the line

To match the first three items (including empty onces) I would do:

\v^([^,]*,){2}[^,]*

If the third item must ends with, then you do:

\v^([^,]*,){3}

Remark: in your example ^ is not matching multiple times but (^|,) is matching multiple times.

Remark: you can prefix the () with % to avoid that () captures. More information with: :help /\%

2
  • yeah... but then the last item would be different ie not ending with , . there are other codes using the regex result, so if it can be (^|,)[^,]* style to match an item that would be much easier...
    – athos
    Commented Oct 16 at 16:31
  • If the third item must end with , then the answer would be: \v^([^,]*,){3} Commented Oct 16 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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