Reputation: 67440
This is for Visual Studio code, but I'm not sure how relevant that is.
Here's my regex: cost:(\d\d)
I'm trying to multiply that number by 100. e.g., change cost:25
to cost:2500
But if I try this replacement, it thinks I'm asking for group #100, instead of group #1 and two zeros: cost:$100
changes cost:25
to cost:$100
. If I put a space after the two zeros, it replaces it with this: cost:25 00
. Is there a way to tell the regex engine where the group name stops?
I've tried replacing with cost:${1}00
, but that doesn't work. It changes it to cost:${1}00
:
Upvotes: 2
Views: 777
Reputation: 56819
On VS Code 1.51.1, this solution works for Replace (current file) and Replace in Files:
Use $0
to refer to the whole match:
Search: cost:\d\d
Replace: $000
As mentioned in the comment, these two methods only works for Replace (current file) but not Replace in Files:
Use $&
to refer to the whole match:
Search: cost:\d\d
Replace: $&00
Use $1
to refer to the first capturing group:
Search: cost:(\d\d)
Replace: cost:$100
For the regular Replace, the replacement string parsing rule is the same as JavaScript. Since we don't have 10 or 100 capturing groups in the regex, the replacement string is parsed as $1
(whatever matched in group 1) followed by literal 00
However, for Replace in Files, the replacement only works when there is only 1 digit following the $1
(cost:$10
). Once there are more than 2 digits, it's treated as literal string replacement
I played around with named capturing groups - while they are recognized in the search field, I can't refer to it in replacement string. Common syntax such as ${group}
and $<group>
doesn't work.
After testing a bit more, I find some weird bugs with how Replace in Files is implemented.
This straight-forward method with named capturing group doesn't work:
Search: cost:(?<n>\d\d)
Replace: cost:$<n>00
But we can coax it to work by mixing named capturing group replacement with numbered group replacement:
Search: cost:(?<n>\d\d)()
Replace: cost:$2$<n>00
We can also apply this trick to get the numbered group replacement to work:
Search: cost:(\d\d)()
Replace: cost:$2$100
Seems that there is a bug when the replacement string only includes a single replacement token.
Upvotes: 3
Reputation: 182331
You have run into this bug discussed here: VSCode Regex Find/Replace In Files: can't get a numbered capturing group followed by numbers to work out
and the filed issue: https://github.com/microsoft/vscode/issues/102221
which was unfortunately closed with "ask on SO response" despite having originated here. Although there are workarounds - also noted in the So link here, you can still comment on the issue and ask it to be reopened.
The weird thing is that if you add just one digit like cost:$10
it works just fine - that is why I consider this a bug.
Upvotes: 0
Reputation: 20867
Instead of using groups, why not match the zero-width character using lookbehind?
(?<=cost:\d\d)
00
Upvotes: 3