I have a quesion about regexp in tcl:
first output: TIP_12.3.4 %
second output: TIP_12.3.4 %
and sometimes the output maybe look like:
first output: TIP_12 %
second output: TIP_12 %
I want to get the number 12.3.4 or 12 using the following exgexp:
output: TIP_(/[0-9].*/[0-9])
but why it does not matches 12.3.4 or 12%?
Your problem is that
/is not special in Tcl’s regular expression language at all. It’s just an ordinary printable non-letter character. (Other languages are a little different, as it is quite common to enclose regular expressions in/characters; this is not the case in Tcl.) Because it is a simple literal, using it in your RE makes it expect it in the input (despite it not being there); unsurprisingly, that makes the RE not match.Fixing things: I’d use a regular expression like this:
output: TIP_([\d.]+)under the assumption that the data is reasonably well formatted. That would lead to code like this:Everything not in parentheses is a literal here, so that the code is able to find what to match. Inside the parentheses (the bit we’re saving for later) we want one or more digits or periods; putting them inside a square-bracketed-set is perfect and simple. The net effect is to store the
12.3.4in the variabledottedDigits(if found) and to yield a boolean result that says whether it matched (i.e., you can put it in anifcondition usefully).NB: the regular expression is enclosed in braces because square brackets are also Tcl language metacharacters; putting the RE in braces avoids trouble with misinterpretation of your script. (You could use backslashes instead, but they’re ugly…)