1

I am trying to do a search and replace on a large database file where some of the urls are escaped and some not, e.g.:

http://www.example.com
http:\\/\\/www.example.com

I thought I could use a simple character class in a regex like this:

%s~http\(:[/\\]+www.example.com\)~https\1~g

But won't work no matter how I escape it. Can I use character classes in vim search and replace? If not, how can I match the url so that any amount of backslashes and forward slashes are matched?

1
  • 1
    You are missing a backslash between [/\\] and +. + just means a literal plus sign, \+ is used for repetition of the preceding atom. Jul 28, 2017 at 6:21

2 Answers 2

1

In your search pattern of the :s part you are looking for www. which is not part of your source. So it won't match. Better would be to make that part optionally:

%s~http\(:[/\\]\+\(www.\)\?example.com\)~https\1~g

or even better:

%s~http:[/\\]\+\(\(www.\)\?example.com\)~https://\1~g

which will also normalize the slashes following the protocol part of your URI.

4
  • sorry, you're right but that's only because I changed the url for purposes of the question. the real url has 'www'. updating question. are you able to get character class to work in vim? I am not... maybe a version thing? which version are you using that allows this? Jul 23, 2017 at 0:03
  • that should simply work. Does it not work with my suggested regex? If it does, perhaps your real URL is somewhat different? Jul 23, 2017 at 19:30
  • thanks - actually it does work and the first one is better since it keeps the slash pattern whether it's escaped or not. the thing i'm confused about now is that in this accepted answer (vi.stackexchange.com/a/4117/13528) he states "in Vim you can't use character classes". Is it wrong? Thanks for your input Jul 23, 2017 at 23:21
  • @billynoah the comment from the other answer was meaning you cannot use those special atoms like \s or \d in a character class. In Vim regex this [\d] means either a backslash or a d but does not stand for the character class [0-9] Jul 24, 2017 at 19:54
0

Figured this out myself using alternation and \z for pattern matching:

%s,\zshttp\ze:\(/\|\\\)\+www.example.com,https,g

Hope this helps someone.

Your Answer

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

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