简体   繁体   中英

Issue with Visual Studio find and replace with RegEx?

I may be losing my mind here, but the regex I am using works in JavaScript and other languages, but isn't working in VS2013.

The problem

I want to find and replace all phone numbers with a new phone number, keeping the spaces in the same places where present.

Example

The current phone number 08453333666 is being replaced by 03035555111. The number might be expressed as 0845 333 3666, 08453 3336 66, or any other variation. In the examples given, I want to replace them with the spaces at the same index, so 0845 333 3666 becomes 0303 555 5111 and 08453 3336 66 becomes 03035 5551 11.

The RegEx

I am using

0( *)8( *)4( *)5( *)3( *)3( *)3( *)3( *)6( *)6( *)6

For the find and

0$13$20$33$45$55$65$75$81$91$101

For the replace.

This seems to work in JavaScript and other languages, but not in VS2013 find and replace in files.

Any ideas?

You need to use ${<BACK-REFERENCE_ID>} in the replacement to indicate a correct back-reference:

0${1}3${2}0${3}3${4}5${5}5${6}5${7}5${8}1${9}1${10}1

See demo

The point is that the regex engine sees $13 and starts looking for the 13th captured group, and since it is missing, this $13 is treated as a literal. And so on.

See Substituting a Numbered Group :

All digits that follow $ are interpreted as belonging to the number group. If this is not your intent, you can substitute a named group instead. For example, you can use the replacement string ${1}1 instead of $11 to define the replacement string as the value of the first captured group along with the number "1" .

...

If number does not specify a valid capturing group defined in the regular expression pattern, $number is interpreted as a literal character sequence that is used to replace each match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM