0

In VI I need to replace a pattern that looks like this:

seq- followed by exactly 24 chars (can be 0-9, a-z, A-Z only) followed by / followed by some number of (0-9, a-z, A-Z). So an example string would be:

seq-BzFk78qrJBkbnv1KkxppsfG4/92191_A_B

I want to replace the above string with a fixed string:

seq-ID/NUM_ID

How do I do this in Vi or Vim? I tried a few things like

:%s/seq-[a-zA-Z0-9]{24}\/[a-zA-Z0-9]{+}/seq-ID\/NUM_ID

But it doesn't work.

1

1 Answer 1

6

There are many problems with your regex.

  1. {24} will not match 24 of the previous atom, it will match the text {24}. I doubt this is what you want. You need a backslash e.g. \{24}. Additionally you could enable "Very magic", e.g. \v{24}

  2. In your example, the text after the slash has underscores in it, e.g. 92191_A_B. Change [a-zA-Z-0-9] to [a-zA-Z-0-9_]

  3. "One or more" is \+, not {+}.

There are also some style problems.

  1. If you are going to search for something containing slashes, you should use a different separator, e.g.

    :%s;seq-[a-zA-Z0-9]{24}/[a-zA-Z0-9]{+};seq-ID/NUM_ID
    

    For more readability.

  2. Don't use [a-zA-Z0-9_] when you could just use \w. I would also use this in place of [a-zA-Z0-9] unless it's possible that underscores will be in there, and you want to avoid matching this. In this case, \c[a-z0-9] is also shorter

Putting this all together, I would recommend going with:

:%s;\vseq-\w{24}/\w+;seq-ID/NUM_ID

I would also highly recommend reading through vim regex. One of the best quick intros to vim's regex engine I have ever seen. I have it bookmarked in my browser at all times for quick reference.

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.