Regex Match Spaces and Periods Between Specified Strings

38 Views Asked by At

I am trying to match all characters that would invalidate the tags in the frontmatter of my obsidian markdown file, so that I can replace them with underscores. The file's metadata looks like this:

tags: [book,timeline, J. D. Salinger, Margaret Atwood, O'Connell]

Ideally, I'd be able to turn this into:

tags: [book,timeline,J_D_Salinger,Margaret_Atwood,O_Connell]

Is there any way to do this?

I was able to match all of the content between the square braces, but I was unable to isolate the spaces.

1

There are 1 best solutions below

0
DuesserBaest On

Try:

(?<!,)[ .']+(?!.*\[)

and replace with

_

See here: https://regex101.com/r/Z54P12/latest

(?<!,) ensures no comma is preceeding (avoids a, b,... turning into a,_b,...)

[ .']+ matches a set of special characters (add to it as you see fit)

(?!.*\[) ensures that no special character/space before the [...] section is replaced