1

For example, we have a file with all kind of domain names about 800 lines. we would like to using vim to quickly find all the domain names that start www.example.** where ** is 2 letters for any kind.

example.site"
example.link]"
example.example'
example.ex'
example.xx]"'

Now we can search in vim with term example., but how can we wildcard to match, so we can find example.ex' and example.xx]" in our example above ?

we don't want to highlight string like

> example.site" 
> example.link]" 
> example.example'

just example.ex and example.xx (it would be better if we can delete all others and leave the only matched string)

2
  • you can use :/example.[a-zA-Z][a-zA-Z]/ I suppose any of regexp can just work fine
    – francois P
    Commented Nov 27, 2021 at 17:41
  • Yes. You are right. I actually need to improve my question.
    – Maxfield
    Commented Nov 27, 2021 at 17:46

1 Answer 1

2

You could use:

/example\.\w\w\W

To search for 'example.' followed by two 'word characters' \w and then by a 'non-word character' \W

To delete all lines not matching the pattern you can do:

:v/example\.\w\w\W/delete

Or just:

:v/example\.\w\w\W/d

Or using the g[lobal] command with negation !:

:g!/example\.\w\w\W/d

The 3 above commands all will turn this:

example.site"
example.link]"
example.example'
example.ex'
example.xx]"'

into this:

example.ex'
example.xx]"'

Update

For dealing with cases where these patterns are on the same line like this:

example.site"
example.example' example.ex' example.link]"
example.xx]"'

You can use a search pattern like this:

/example\.\w\w\w[^ ]* \?

The way this works is to find 'example.' followed by three 'word characters' followed by any number of characters which are not spaces [^ ]* and ending with an optional space \?.

You can therefore replace the matches with nothing (the g means apply this substitution for every match on the line, not just the first one it finds):

:%s/example\.\w\w\w[^ ]* \?//g

to get:


example.ex' 
example.xx]"'

(and you could also remove blank lines with :g/^$/d. In fact, you could chain this together using the | and do it all in one with :%s/example\.\w\w\w[^ ]* \?//g | %g/^$/d)

3
  • Thank you. so it only highlight the desired result. (not sure why, maybe I have different vim config file or on a mac).
    – Maxfield
    Commented Nov 27, 2021 at 18:14
  • I know why now. Those desired strings not are actually in a separated lines. since there are some in the same lines. like example.example' example.ex' example.xx]"' example.ex' example.xx]"' are all in one line. But it helps a lot alreay. Thank you.
    – Maxfield
    Commented Nov 27, 2021 at 18:21
  • @Maxfield I updated the answer to cover the case of multiple patterns on the same lines.
    – mattb
    Commented Nov 27, 2021 at 18:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .