Home > front end >  Regex to replace whitespace in Markdown URLs
Regex to replace whitespace in Markdown URLs

Time:11-04

I've a bunch of Markdown links with whitespace, and I need to replace the whitespace with . So far I've hacked a few solutions, but none that work in VSCode, or do exactly what I'm looking for.

This is the URL format conversion I need:

[My link](../../_resources/my resource.jpg)
[My link](../../_resources/my resource.jpg)

\s (?=[^(\)]*\)) will work on any whitespace inside brackets - but gives false positives as it works on anything with brackets.

(?:\]\(|(?!^)\G)[^]\s]*\K\h does the job, but I'm getting some "Invalid Escape Character" messages in VSCode, so I assume the language isn't compatible.

I've been trying to identify the link on the characters ]( but as I'm relatively new to regex, struggling a bit.

I tried with this regex: (?<=\]\()s\ as this (?<=\]\(). correctly identifies the url, but it doesn't work.

Where am I going wrong here? Thanks in advance!

EDIT: VSCode find in files doesn't support variable length lookbehind, even though find/replace in the open file does support this. Open to any other solutions before I dive into writing a script!

CodePudding user response:

VSCode regex does not support \K, \G, or \h, but it does support Lookbehinds with non-fixed width. So, you may use something like the following:

(?<=\]\([^\]\r\n]*)[^\S\r\n] 

enter image description here

Details:

  • (?<=\]\([^\]]*) - a positive lookbehind that matches a location that is immediately preceded with ]( and then any zero or more chars other than ]
  • \s - any one or more whitespace chars (other than line break chars in Visual Studio Code, if there is no \n or \r in the regex, \sdoes not match line break chars)
  • (?=[^()]*\)) - a positive lookahead that matches a location that is immediately followed with zero or more chars other than ( and ) and then a ) char.

Since you are using it in Find/Replace in Files, this lookbehind solution won't work.

You can use Notepad with

(\G(?!\A)|\[[^][]*]\()([^()\s]*)\s (?=[^()]*\))

and $1$2 replacement pattern. In Notepad , press CTRL SHIFT F and after filling out the necessary fields, hit Replace in Files.

See the sample settings:

enter image description here

  • Related