[英]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 我希望sub的值是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). 稍后会泄漏到.*
,这是所使用的RE引擎的功能(自动理论而非基于堆栈的理论)。
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 -
). 因为Tcl具有未锚定的正则表达式(默认情况下)并尽快开始匹配,所以从字符串的第一个-
到结尾的贪婪匹配是完美的(在-
之后给sub
分配了所有内容)。 That's a very simple RE: -(.*)
. 那是一个非常简单的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.