简体   繁体   中英

Using regex to fetch a value

I have a string:

set a "ODUCTP-1-1-1-2P1"
regexp {.*?\-(.*)} $a match sub

I expect the value of sub to be 1-1-1-2P1

But I'm getting empty string. Can any one tell me how to properly use the regex?

The problem is that the non-greediness of the .*? is leaking over to the .* later on, which is a feature of the RE engine being used (automata-theoretic instead of stack-based).

The simplest fix is to write the regular expression differently. Because Tcl has unanchored regular expressions (by default) and starts matches as soon as it can, a greedy match from the first - to the end of the string is perfect (with sub being assigned everything after the - ). That's a very simple RE: -(.*) . To use that, you do this:

regexp -- {-(.*)} $a match sub

Note the -- ; it's needed here because the regular expression starts with a - symbol and is otherwise confused as weird (and unsupported) option. Apart from that one niggle, it's all entirely straight-forward.

$str = "ODUCTP-1-1-1-2P1";
$str =~ s/^.*?-//;
print $str;

or:

$str =~ /^.*?-(.*)$/;
print $1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM