tags:

views:

54

answers:

1

Hey everybody,

I am a novice TCL programmer. Here I go - My 1st post with stackoverflow forum.

I would like to write a regular expression that matches any & only the strings starts with character A and ends with B. Whatever the characters coming inbetween should be displayed. For instance AXIOMB as an input from the user which starts with A & end with character B.

Here is my try

regexp { (^A([C-Z]+)B$)}

Thank you

+2  A: 

You're very close:

set stringToTest "AXIOMB"
set match [regexp {^A([C-Z]*)B$} $stringToTest -> substring]
if {$match} {
    puts "The middle was $substring"
}

(The -> is actually an unusual variable name. But here I'm using that symbol because it looks better than using the otherwise-equivalent someRandomDummyVariable. :-))

If you're seeking to get the string to test from the command line or the console, here's how:

Command line arguments (without the name of the Tcl interpreter or the script) are presented as a list in the global argv list variable. The first one is thus [lindex $::argv 0].

A line can be read from the console via the gets command.

set line [gets stdin]; # you can use other channel names too, of course

Note that, unlike in C, gets in Tcl is strongly defended against buffer overflows and the (almost) full power of scanf() is about equivalent to scan [gets stdin] ... (except for some formats excluded for security reasons).

Donal Fellows
@ Thank you very much Donal Fellows. Much appreciated. Just would like to know how to get this string from the user in Command line. In 'C' we use like scanf.
Will edit that in.
Donal Fellows