Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a space around equals-sign if not already whitespace

I am trying to work out a Perl regex for adding in a space around equals sign ("=") - but only if there isn't a space there already:

var myVariable="thisValue" -> var myVariable = "thisValue"
var mySecondVariable ="thisValue" -> var mySecondVariable = "thisValue"
var myThirdVariable= "thisValue" -> var myThirdVariable = "thisValue"

I have managed to replace valid characters with a space.

I have managed to have double-spaces before a "="... and nothing after.

like image 575
Gavin Baumanis Avatar asked Dec 10 '25 23:12

Gavin Baumanis


1 Answers

This replaces all optional whitespace around = (or none) with a single space before and after =:

use warnings;
use strict;

while (<DATA>) {
    s/\s*=\s*/ = /g;
    print;
}

__DATA__
var myVariable="thisValue" -> var myVariable = "thisValue"
var mySecondVariable ="thisValue" -> var mySecondVariable = "thisValue"
var myThirdVariable= "thisValue" -> var myThirdVariable = "thisValue"

Prints:

var myVariable = "thisValue" -> var myVariable = "thisValue"
var mySecondVariable = "thisValue" -> var mySecondVariable = "thisValue"
var myThirdVariable = "thisValue" -> var myThirdVariable = "thisValue"
like image 104
toolic Avatar answered Dec 13 '25 15:12

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!