Tamilan
Tamilan

Reputation: 981

regsub -all for multiple match is not working

Using the below regular expression trying to capure pf2(y,[],[],n) and insert [],[] after second square bracket [] as like pf2(y,[],[],[],[],n)

    set test {hk,pf2(y,[],[],n),[y:0],flags(no,no,no)),hk,pf2(y,[],[],n),[y:0],flags(no,no,no))}

the below regsub is working for the last match, but it is not matching all the match

    regsub -all -- {,(pf2\([y|n]),\[(.*)\],\[(.*)\],(.)} $test {,\1,[\2],[],[],[\3],\4} test

Actual output:

    hk,pf2(y,[],[],n),[y:0],flags(no,no,no)),hk,pf2(y,[],[],[],[],n),[y:0],flags(no,no,no))

Expected Output:

    hk,pf2(y,[],[],[],[],n),[y:0],flags(no,no,no)),hk,pf2(y,[],[],[],[],n),[y:0],flags(no,no,no))

Please advice

Upvotes: 0

Views: 452

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

The problem is that the regular expression is greedy and matches as much as it can. We can see this if we do this slight variation (inserting highly visible markers is a good way to diagnose RE problems when the wrong thing is being matched):

% regsub -all {,(pf2\([y|n]),\[(.*)\],\[(.*)\],(.)} $test {>>>>,\1,[\2],[],[],[\3],\4<<<<}
hk>>>>,pf2(y,[],[],n),[y:0],flags(no,no,no)),hk,pf2(y,[],[],[],[],n),[y:0],f<<<<lags(no,no,no))

Changing the greediness of the quantifiers (.* to .*?) makes it do what you expect:

% regsub -all -- {,(pf2\([y|n]),\[(.*?)\],\[(.*?)\],(.)} $test {,\1,[\2],[],[],[\3],\4}
hk,pf2(y,[],[],[],[],n),[y:0],flags(no,no,no)),hk,pf2(y,[],[],[],[],n),[y:0],flags(no,no,no))

Upvotes: 1

Related Questions