1

I'm trying to capture the term ISomething only when it isn't immediately preceded by a full stop . however my search is capturing the preceding letter or space. I'm using javascript style regex (vscode search to be exact).

My aim is to replace ISomething with Namespace.ISomething without touching existing namespaces.

Live example

My search sample

Api.Resources.Things.Bits.ISomething     //doesn't match
something : ISomething
List<ISomething>
something:ISomething
isomething                               //doesn't match

My regex

[^\.](ISomething)

My matches, the first captures the whitespace, the second the arrow, third the bracket.

  ISomething
 <ISomething
 :ISomething

How (and why) can i just get the word ISomething in all of the above?

gingerbreadboy
  • 6,763
  • 5
  • 29
  • 60
  • 1
    Could you please clarify what you want to achieve: replace `ISomething` with something else? Then use `(^|[^.])ISomething` and replace with `$1` to remove those instances. Or replace with `$1NEW STRING` to replace with a new string. – Wiktor Stribiżew Jan 03 '18 at 12:11
  • My aim is to replace ISomething with Namespace.ISomething without touching existing namespaces. – gingerbreadboy Jan 03 '18 at 12:18
  • So, you may try [`(^|[^.])\b(ISomething)\b` to replace with `$1Namespace.$2`](https://regex101.com/r/v5c5mY/1) – Wiktor Stribiżew Jan 03 '18 at 12:19

3 Answers3

3

UPDATE

You can use infinite-width lookahead and lookbehind without any constraint beginning with Visual Studio Code v.1.31.0 release, and you do not need to set any options for that now.

So, the solution can look like

Find what: \b(?<!\.)ISomething\b
Replace with: Namespace.$&

enter image description here

The (?<!\.) must be after \b for better performance (in order not to perform lookbehind check at each position in a string) and is a negative lookbehind that matches a position that is not immediately preceded with a literal .. The $& in the replacement is a whole match value backreference/placeholder.

With older versions you may use

Find what: (^|[^.])\b(ISomething)\b
Replace with: $1Namespace.$2

See the regex demo and the VSCode settings below:

enter image description here

NOTE that the Aa (case sensitivity) and .* (regex mode) options must be ON.

After clicking Replace all, the results are:

enter image description here

Regex details

  • (^|[^.]) - Group 1: either the start of the line/string or any char other than .
  • \b - a word boundary
  • (ISomething) - Group 2: the word ISomething
  • \b - a word boundary
Community
  • 1
  • 1
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
1

if supported \K may be what you are looking for:

[^\.]\KISomething
Nahuel Fouilleul
  • 16,821
  • 1
  • 26
  • 32
1

You could use a negative lookbehind

(?<!\.)ISomething basically this will match any ISomething that is not preceded by a .

Benjamin Udink ten Cate
  • 12,052
  • 3
  • 43
  • 63