[regex]::replace('test test','^(.*?)test', 'barf')
returns ‘barf test’
Why doesn’t it replace all occurrences of ‘test’? This must have something to do with the position at which a subsequent replace iteration begins.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Quick answer: you anchored it at the beginning of the input (
^) and your first group ((.*?)) did not capture anything (since the first occurrence oftestwas found right after the beginning of line and you use a lazy quantifier — furthermore you don’t use the capture in your replacement string. Had you used a “normal” quantifier, the last occurrence oftestwould have been replaced).Long answer: a regex never needs to match the whole input, only the parts which are necessary. What’s more, when cycling through an input, the regex engine will start the next round from the position where it successfully completed a match.
Here, you want to replace a sequence of characters which is
test. Note that it will also means thattestosteronewill be matched (oruntested). If you want to matchtestas a “word”, use the word anchor\b.This works (
tested on Powershell v2):The engine in action looks something like this: