Skip to content

Instantly share code, notes, and snippets.

@SjorsO
Last active December 25, 2022 12:07
Show Gist options
  • Save SjorsO/c4e81367ddb59610a2252c754cd47b7d to your computer and use it in GitHub Desktop.
Save SjorsO/c4e81367ddb59610a2252c754cd47b7d to your computer and use it in GitHub Desktop.
Obsidian paste formatter - patterns help

This is a very basic tutorial on how to use patterns in my Obsidian paste formatter plugin. The patterns are default Javascript regexes, so for for more help, you can also google "javascript regex tutorial".

Let's take this pattern as an example:

https://github.com/.+?/.+?/issues/([0-9]+)

This pattern matches links to GitHub issues, for example:

https://github.com/sjorso/obsidian-paste-formatter/issues/195

This pattern contains these regex patterns:

  • .+?
  • ([0-9]+)

Let's break .+? down:

  • A . matches exactly one of any character (as in, text, numbers, spaces, new lines, etc.)
  • A + modifies the previous character, changing it from exactly one, to one or more (so in this case .+ = one or more of any character)
  • The ? makes the matching lazy. It means that the pattern will stop as soon as possible (a little bit hard to explain, but when using . this is usually what you want).

Tip: you can almost always use .+? to match dynamic text.

Now for ([0-9]+):

  • The (...) captures this text as a group. More on this later.
  • The [0-9] is a range, matching any character (or number, in this case), between 0 and 9. It matches this exactly once.
  • Like before, the + changes it from matching exactly one, to one or more

This pattern gives us the following results:

Pattern: https://github.com/.+?/.+?/issues/([0-9]+)

Pasted text: https://github.com/sjorso/obsidian-paste-formatter/issues/195 

Capture groups:
- $0: https://github.com/sjorso/obsidian-paste-formatter/issues/195
($0 is always the full matched text)

- $1: 195
(this is thanks to the parentheses around `[0-9]+`)

Formatting

We can use the capture groups from our pattern like this:

{$0} {$1}

This would give us this result:

https://github.com/sjorso/obsidian-paste-formatter/issues/195 195

More usefully, we can format this GitHub link into a markdown link, with the issue number as the label:

Pattern: https://github.com/.+?/.+?/issues/([0-9]+)

Pasted text: https://github.com/sjorso/obsidian-paste-formatter/issues/195 

Format: [#{$1}]({$0})

Result: [#195](https://github.com/sjorso/obsidian-paste-formatter/issues/195)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment