0

I have a variable test with value *string*, I am trying to replace * with .* like this

set test=%test:*=.*%

but I get an error saying =.*% was unexpected at this time.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Bricktop
  • 533
  • 3
  • 22

1 Answers1

1

* is a wildcard in variable replacement when using at the start position, so you can't replace them like this

::Delete the character string 'ab' and everything before it
   SET _test=12345abcabc
   SET _result=%_test:*ab=% 
   ECHO %_result%          =cabc

::Replace the character string 'ab' and everything before it with 'XY'
   SET _test=12345abcabc
   SET _result=%_test:*ab=XY% 
   ECHO %_result%          =XYcabc

   SET _test=The quick brown fox jumps over the lazy dog

   :: To delete everything after the string 'brown'  
   :: first delete 'brown' and everything before it
   SET _endbit=%_test:*brown=%
   Echo We dont want: [%_endbit%]

How-To: Edit/Replace text within a Variable

For example with your string *string* it can be used to remove the left or right part like this

D:\>echo %test%
*string*

D:\>echo %test:*str=spr%
spring*

D:\>echo %test:*r=st%
sting*

To do a general replacement you should use jrepl which is a lot more versatile

JREPL.BAT - regex text processor with support for text highlighting and alternate character sets

Possible alternatives:

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • I have jrepl but how do I use for a variable? – Bricktop Nov 28 '19 at 10:43
  • 1
    @Bricktop `echo %test% | jrepl "\*" ".*"` – phuclv Nov 28 '19 at 10:51
  • no I mean how do I record the change into new/same variable so I won't have to do this everywhere I use it? – Bricktop Nov 28 '19 at 10:56
  • 1
    @Bricktop use `for /f` [How to set commands output as a variable in a batch file](https://stackoverflow.com/q/6359820/995714). Or read the other question, there are many other ways to do that – phuclv Nov 28 '19 at 10:57