With a bit of tinkering and a careful eye, you can do some wonderful stuff with -replace! Named Match Groups Note that the match group is respected, pulling the first word, and then the entire match is retrieved again and reinserted.Īs you can imagine, this can be made incredibly complex and strange very quickly. PS > 'hello world' -replace '(\w ) \w ', '$1 $0' hello hello world You might recall from my previous post on regex that PowerShell has a $matches variable, where $matches refers to "the complete matched string". Why is it 1-indexed, you might ask, when literally everything else in PowerShell is 0-indexed? In this context, that variable refers to "the first match group". Instead, this string is given to the underlying regex method, which does recognise it as a variable. PowerShell isn't processing that $ symbol, and we don't want it to that's why I used single quotes to create a literal string. This isn't PowerShell, at least not where it counts here. While that syntax might look familiar to you from PowerShell's variables, don't be fooled. Second, we don't get the characters $1 back in our result. There are two things to note in the above example.įirst of all, that pattern would match the entire string, so it would normally just remove the string. PS > $string = 'You lost your mind in the sound.' PS > $string -replace '.*(\w )\.', '$1' sound
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |