6

I'm trying to use the Visual Studio editors Regular Expressions to find and replace text using capture-groups, but have run into a problem.

I'm trying to find and capture a set of 5 Alpha-Numerics:

(\w{5})

And search-replace that group to append a "1" after it:

$11

Here I really mean $1 The Captured Group + 1 Text to append

Examples:

 227TW ==> 227TW1
 1053X ==> 1053X1

However, it obviously interprets $11 as "Capture Group Eleven".

How can I properly make the Search/Replace understand that $1 and 1 are separate elements?

Things I've tried, that failed:

$1(1)  : 227TW ==> 227TW(1)
$1\1   : 227TW ==> 227TW\1
$1 1   : 227TW ==> 227TW 1
$1^1   : 227TW ==> 227TW^1
($1)1  : 227TW ==> (227TW)1

2 Answers 2

8

Turns out the right answer is:

${1}1

The curly-braces around the number identify the capture group without confusing it with the next digit.

4
  • 2
    great answer!! Actually I wanted to suggest to step approach, e.g. first replace to $1##1## or whatever string you won't find in your input, then replace ##1##to 1 Feb 4, 2019 at 21:27
  • Not sure if this doesn't work anymore or if I'm doing something wrong but that won't work for me - it doesn't match a group and replaces with ${1} litterally.
    – Ten
    Jun 8, 2022 at 22:50
  • @Ten: It sounds like you do not have the "Use Regular Expressions" checkbox selected.
    – abelenky
    Jun 8, 2022 at 23:01
  • 1
    @abelenky thank you for your answer - unfortunately I do: it matches using the regex and it's just the capture group replacements that aren't identified as such as soon as I add the {} :(
    – Ten
    Jun 14, 2022 at 17:03
1

Not sure if VS supports lookbehind, but if it does, you can use:

  • Find: (?<=\w{5}) zero-length assertion to make sure we have 5 word characters before current position
  • Replace: 1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .