5

I want to build regex expression in VS Code which returns all the phrases in the whole solution which contain a given string(please keep in mind that it can contain special characters) and not ends with given string e.g. Contains /webhelp but not ends with /

Matches:

/server/webhelp

blah/webhelp#

Doesn’t match

/server/webhelp/

server#webhelp/

Im not an expert in Regex, I’ve tried to build something like:

(?=/webhelp)(?=.*(?<!/)$)

But it doesn’t work.

GoldenAge
  • 2,918
  • 5
  • 25
  • 63

2 Answers2

4

Here's a slightly shorter version of the regex:

/webhelp(?!/)

It simply matches '/webhelp' unless it's followed by a slash.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
3

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.

With earlier versions, you may use lookaheads. The regex that should match what you need is

/webhelp(?!.*/$).*$

enter image description here

Details

  • /webhelp - a literal substring
  • (?!.*/$) - a negative lookahead that makes sure the line does not end with /
  • .*$ - the rest of the line.

It still works even in Find in files:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I checked this and it also works for me when I try to search in a single file. Don't know why it doesn't work for the global search engine(Ctrl+Shift+F). – GoldenAge Nov 20 '18 at 13:02
  • @GoldenAge My solution still works, I added another screen. The other solution does not check for `/` at the end of the line. Probably, you did not explain your requirements well. – Wiktor Stribiżew Nov 20 '18 at 13:10
  • I've created the same project as you and your expression works properly in it but it doesn't work in my main project don't know why! This is very weird! Anyway, you have an upvote from me. – GoldenAge Nov 20 '18 at 13:31
  • @GoldenAge Ok, I see, it is fine. Let's hope the next release will have a more "stable" and cooler regex support. Happy coding. – Wiktor Stribiżew Nov 20 '18 at 13:31