1

I have this string:

svpts-7-40.0001

And I need to remove the second '-' from this. Basically I am fetching values like these which would come with double '-' SOMETIMES. So if such variables are seen then I have to remove the second '-' and replace the same with '.' , so the string should look like:

svpts-7.40.0001

[EDIT] I have tried:

% set list1 [split $string -]
svpts 7 40.0001
% set var2 [join $list1 .]
svpts.7.40.0001
%
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
vinay
  • 53
  • 1
  • 8
  • tried split and join: % set list1 [split $string -] svpts 7 40.0001 % set var2 [join $list1 .] svpts.7.40.0001 % but joins on basis of . for all items it has to happen only for second hyphen(-) @Jolta – vinay Nov 10 '16 at 11:49
  • 'need to remove multiple "-"' -- does that mean if there can be instances where you need to remove more than one of the hyphens? – Jerry Nov 11 '16 at 04:58

2 Answers2

1

Here's a regular expression that will change only the 2nd hyphen:

% regsub -expanded {( .*? - .*? ) -} "svpts-7-40.0001" {\1.}
svpts-7.40.0001

% regsub -expanded {( .*? - .*? ) -} "svpts-7_40.0001" {\1.}
svpts-7_40.0001

% regsub -expanded {( .*? - .*? ) -} "svpts-7-40.0001-a-b-c" {\1.}
svpts-7.40.0001-a-b-c
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • that helped and most optimal, costly operation but still gets pefect output thanks glenn – vinay Nov 11 '16 at 11:09
0

Try

% set data svpts-7-40.0001
svpts-7-40.0001
% regexp {([^-]*-)(.*)} $data -> a b
1
% set b [string map {- .} $b]
7.40.0001
% set newdata $a$b
svpts-7.40.0001

The above code changes every hyphen after the first. To change only the second hyphen, one can do this:

set idx [string first - $data [string first - $data]+1]
set newdata [string replace $data $idx $idx .]

or this:

set idxs [lindex [regexp -inline -all -indices -- - $data] 1]
set newdata [string replace $data {*}$idxs .]

The first snippet is well-behaved if the data string doesn't contain at least two hyphens; the other needs some kind of checking to avoid throwing an error.

Documentation: lindex, regexp, set, string, {*} (syntax), Syntax of Tcl regular expressions

Syntax of Tcl index expressions:

  • integer zero-based index number
  • end the last element
  • end-N the nth element before the last element
  • end+N the nth element after the last element (in practice, N should be negative)
  • M-N the nth element before element m
  • M+N the nth element after element m

There can be no whitespace within the expression.

Peter Lewerin
  • 13,140
  • 1
  • 24
  • 27