Skip to content

Ideas for a clean, direct regex mirror of -replace, to "keep the match"? #7958

Closed

Description

@HumanEquivalentUnit

An example regex thing I do is to extract the number out of this string: "blah blah blah 456 blah blah".

The available options are all full of syntax, noise, and multiple steps:

  1. if ($text -match '(\d+)') { $matches[1] }
  2. $text | select-string '\d+' | % matches | % value
  3. [regex]::matches($text, '\d+').Value
  4. $text -replace '.*?(\d+).*', '$1'

But if I wanted to /drop/ the number from the string, there's a really clean short direct way to do it:

  1. $text -replace '\d+'

NB. that in this example I could simply use $text -replace '[^\d]' , but coming up with an inverted regex often is not that simple. Especially if there's a string involved, so an inverted character class won't work. It often means separately matching the start and end, andleaving the middle bit unchanged, as I've tried to show in example number 4 above.

This is a pattern I find myself using quite often in the shell, and it bugs me that there's a first class way to get rid of, and swap string content, but not exactly a first class mirror of that, a way to keep some string content.

What I'm dreaming of, is an operator that works like the opposite of -replace, like this:

  1. $text -keep '\d+'

An operator which behaves like [regex]::matches($text, '\d+').Value - i.e. the result would be plain strings, not MatchInfo, not $matches being set somewhere off in memory. If there's one match there's one string output. If there's N matches, then N strings output. No position, no metadata, no nesting. If there's no matches, there's no output (it doesn't return $false). If it's used on an array of strings on the left, it will output the matches from each of them, not filtering the array.

Maybe it could take another parameter like -split does to return only the first N items, so

PS C:\> "abc 123 def 456 ghi 789" -keep '\d+', 2
123
456

Binary operator -keep (or -pluck, -getmatch, -gimme, -matchNgo, -extract, -matchvalues, or whatever name).

Does that exist in other languages? Does anyone wish it did?

Activity

  1. changed the title [-]Ideas for a clean, direct regex way to "keep the match"?[/-] [+]Ideas for a clean, direct regex mirror of `-replace`, to "keep the match"?[/+] on Oct 7, 2018
  2. changed the title [-]Ideas for a clean, direct regex mirror of `-replace`, to "keep the match"?[/-] [+]Ideas for a clean, direct regex mirror of -replace, to "keep the match"?[/+] on Oct 7, 2018
  3. HumanEquivalentUnit commented on Oct 7, 2018

    @HumanEquivalentUnit
    ContributorAuthor

    I wrote this independently before I saw issue #7867. That is still about outputting a chunk of metadata, which is not what I want, but there is talk in the comments of string output, I will chase this up there instead.

  4. jimbobmcgee commented on Mar 13, 2024

    @jimbobmcgee

    But if I wanted to /drop/ the number from the string, there's a really clean short direct way to do it:

    *(I realised later that you are not looking for a way to drop the number, it was just an example that dropping is easy; expand for some historic stuff that is probably unnecessary)*

    You are pretty close with $text -replace '.*?(\d+).*', '$1'. Have you considered:

    PS C:\> $text -replace '(.*?)(\d+)(.*)', '$1$3'
    

    i.e. Capture the prefix as Group 1, the number as Group 2 and the suffix as Group 3; then replace that whole match (prefix through to suffix) with the content of Group1 and Group 3

    This tends to work best when there is only one match in the string, as the subsequent matches get swallowed by the suffix capture.

    Alternatively, an approach I sometimes like is the split/join:

    PS C:\> ($text -split '\d+') -join ''
    

    i.e. Split the source string into an array of substrings, using your expression as the separator, then rejoin the array of substrings using an empty string as the separator.

    I believe it has the effect you are looking for, but it depends how performant you need to be. On a large source data, split/join will probably allocate a significant number of strings.

    Of course, if you just want to drop all numbers from the input, the sanest and simplest is still...

    PS C:\> $text -replace '\d+',''
    

    i.e. Replace all instances of the number with nothing.


    If you are looking for a sane way to keep only the strings that match your pattern, you probably need to write a function. Something like...

    filter Get-MatchString { 
      Param([regex] $Pattern)
      $private:builder = New-Object Text.StringBuilder
      foreach ($private:m in $Pattern.Matches("$_")) {
        [void]$private:builder.Append($private:m.value)
      }
      Write-Output ($private:builder.ToString())
    }
    
    PS C:\> "blah blah blah 456 blah blah" | Get-MatchString '\d+'
    456
    
    PS C:\> "abc 123 def 456 ghi 789" | Get-MatchString '\d+'
    123456789
    

    not $matches being set somewhere off in memory

    In theory, the changes to $Matches should be scoped to inside the function only, and should revert at the end of the function call.


    PS C:\> "abc 123 def 456 ghi 789" -keep '\d+', 2
    123
    456
    

    This is a different problem, and assumes too much about the input string. Unlike the first request, this time you presume that the string should be automatically split on whitespace before it is treated as a list of terms, and only the matching terms should be returned, rather than a combined string.

    If you want significant whitespace to cause the string to split, you should have to say so, and there are already good-enough idiomatic ways to achieve that, e.g...

    PS C:\> "abc 123 def 456 ghi 789" -split '\s+' | where { $_ -match '\d+' } | select -First 2
    123
    456
    

    If there were a -keep operator that behaved as the inverse of -replace , I would expect such an operator to actually return the string, as -replace does...

    PS C:\> "abc 123 def 456 ghi 789" -keep '\d+', 2
    "123456"
    

    only the first N items

    That's easy enough to add to the function...

    filter Get-MatchString { 
      Param(
        [regex] $Pattern, 
        [Int32] $First
      )
      $private:builder = New-Object Text.StringBuilder
      $private:mcount = 0
      foreach ($private:m in $Pattern.Matches("$_")) {
        if ($PSBoundParameters.ContainsKey('First') -and ($private:mcount -ge $First)) { break }
        [void]$private:builder.Append($private:m.value)
        $private:mcount++
      }
      Write-Output ($private:builder.ToString())
    }
    
    PS C:\> "abc 123 def 456 ghi 789" | Get-MatchString '\d+' 2
    123456
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-Answered

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions