2

I have created a regular expression on regex101 that works as expected, however the problem is that one part is apparently not valid in Powershell; the \K.

Essentially I am looking for instances of a string, and returning the entire word after the instance of the string. So here is an example:

\btest\s+\K\S+

This finds every example of the word test and returns the word after it. I did try experimenting with Lookaheads and Lookbehinds, while some of those do work, they are still either returning test or additional unnecessary characters.

Is there a way to replicate the \K in powershell? Or even better, any add-ons that will allow PowerShell to use the \K?

briantist
  • 45,546
  • 6
  • 82
  • 127
shannonjk
  • 45
  • 6
  • While I love the interface of, and have used it many times, RegEx101 does not support .Net versions of RegEx. You should consider using [RegExStorm](http://regexstorm.net) instead. – TheMadTechnician Oct 06 '17 at 18:34
  • Possible duplicate of [Match first executable path in list in PowerShell](https://stackoverflow.com/questions/46587101/match-first-executable-path-in-list-in-powershell) - the title is nothing like, but the core of the question and the accepted answer are about regex `\k` – TessellatingHeckler Oct 06 '17 at 19:29
  • Thank you for the RegExStorm link, that is helpful! – shannonjk Oct 11 '17 at 16:33

1 Answers1

8

What about something like this: (?<=\btest\b)\s+(\w+)\S+

A positive look-behind for test followed by the rest of the stuff you were looking for, and a capture group for the following word.

PowerShell uses the .Net RegEx engine, and it doesn't support \K as you know it (it's used for referencing named capture groups in .Net). You can't change that.

You could possibly use some third party implementation of regex that's compatible with .Net, but it seems unlikely that there is such a thing since in general .Net has a pretty good and full-featured engine.

briantist
  • 45,546
  • 6
  • 82
  • 127
  • Thank you Briantist, this did solve the problem! It was tricky at first because select-string using this regex pattern, wasn't working as intended. I eventually stumbled upon using [regex]::matches(,) in order to make this work. It appears not all methods of using regex in powershell are equal :). – shannonjk Oct 11 '17 at 16:31
  • @shannonjk all of the methods use the same underlying engine, but they return their results in different ways and may use different defaults. `Select-String` for example returns its own match objects (not just the string). The operator `-match` returns a bool for a single left-hand operand or an array for an array LH-op. `-replace` returns the replaced string. Some populate `$Matches`, some don't. But under the hood they all use the .Net regex engine. – briantist Oct 11 '17 at 17:49