1

I am able to write a regex expression to find all underscores in a VS SQL Project.

\[[a-z]+\s[a-z]+\] (looks inside a string that starts and ends with []).

I need a regex replace expression in VS so I can replace in files so it will replace all spaces with underscores _ only inside of [].

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

0

You can use

(?<=\[[^][]*)\s+(?=[^][]*])

Replace with _. See this regex demo.

Details:

  • (?<=\[[^][]*) - a positive lookbehind that matches a location that is immediately preceded with [ and then zero or more chars other than [ and ]
  • \s+ - one or more whitespaces
  • (?=[^][]*]) - a positive lookahead that matches a location that is immediately followed with zero or more chars other than [ and ] and then a ] char.

NOTE: If the spaces right after [ and right before ] and between non-word chars must not be replaced, add word boundaries, \b: (?<=\[[^][]*)\b\s+\b(?=[^][]*]). See this regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Shouldn't you also replace trailing spaces? I only ask because you seemed to write a test for it and didn't match them – Blindy Jul 26 '22 at 16:31
  • @Blindy Exactly, they must not be matched. I added a NOTE. – Wiktor Stribiżew Jul 26 '22 at 16:32
  • The above works great, except for two exceptions, when there is a # at the beginning (i.e. [# My Column Name] comes out as [# My_Column_Name] and if there is a "(", i.e. [My Column (Name)] becomes [My_Column (Name)] – Andrew Hopkinson BI Guru Jul 26 '22 at 16:55