2

I have a range string either in the form of [Numeric1] or [Numeric1:Numeric2] Brackets are part of string as well.

I want to have one regular expression that will give me Start index and another regular expression to give me End Index regardless of the input string.

I have managed to do it, but I was just wondering if there are better ways of doing it. Here is how I did it

#[5]
set range_1 "\[5\]"
#[7:9]
set range_2 "\[7:9\]"

set reg_exp_for_start_index {\[([0-9]*)\]|\[([0-9]*):[0-9]*\]}
set reg_exp_for_end_index   {\[([0-9]*)\]|\[[0-9]*:([0-9]*)\]}

set iStart1 [regsub $reg_exp_for_start_index $range_1 {\1\2}]
puts "Start index for Range 1: $iStart1"

set iEnd1 [regsub $reg_exp_for_end_index $range_1 {\1\2}]
puts "End index for Range 1: $iEnd1"

set iStart2 [regsub $reg_exp_for_start_index $range_2 {\1\2}]
puts "Start index for Range 2: $iStart2"

set iEnd2 [regsub $reg_exp_for_end_index $range_2 {\1\2}]
puts "End index for Range 2: $iEnd2"

I get the expected output which is

Start index for Range 1: 5
End index for Range 1: 5
Start index for Range 2: 7
End index for Range 2: 9

What I don't like is I used or (|) and I have to concatenate the strings as {\1\2}.

l-gr-21
  • 31
  • 2

2 Answers2

2

Use regexp instead.

set range {[5]}
regexp -- {\[([0-9]*)(?::([0-9]*))?\]} $range -> start end
puts "Range: $range"
puts "Start: $start"
puts "End:   $end"

Also, you probably don't want numbers in formats like 007 as ranges, or empty strings either.

regexp -- {\[([1-9]\d*)(?::([1-9]\d*))?\]} $range -> start end

Here's an Ideone demo.

Finally, the -- simply ends switches. It's a habit of mine. And the -> is only an aesthetic trick, relying on the fact that -> is a valid identifier in Tcl. It could just as well be:

regexp -- {\[([1-9]\d*)(?::([1-9]\d*))?\]} $range match start end
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
0

Try this:

set reg_exp_for_start_index {\[([0-9]*)(?::[0-9]*)?\]}
set reg_exp_for_end_index   {\[(?:[0-9]*:)?([0-9]*)\]}

That way you only have one capture group for each regex.

David Knipe
  • 3,417
  • 1
  • 19
  • 19