简体   繁体   English

反向引用在 tcl 正则表达式中不起作用

[英]backreferencing not working in tcl regexp

I am new to regular expressions and tcl and am facing very basic issue from a long time now.我是正则表达式和 tcl 的新手,很长一段时间以来都面临着非常基本的问题。

I am given with the task to find all the characters in given word, whose immediate next character is not identical to this character.我的任务是查找给定单词中的所有字符,其紧接的下一个字符与该字符不同。 I have written following tcl snippet to achieve this:我编写了以下 tcl 片段来实现这一点:

set str "goooo";
set lst [regexp -all -inline {(\w)[^\1]} $str];
puts $lst

I am getting following error:我收到以下错误:

couldn't compile regular expression pattern: invalid escape \ sequence
    while executing
"regexp -all -inline {(\w)[^ \1]} $str"

Is there any other way to use backreferencing in tcl?有没有其他方法可以在 tcl 中使用反向引用?

Backreferences cannot be used inside bracket expressions in any regex flavor.反向引用不能在任何正则表达式风格的括号表达式中使用。 [^\1] matches any char but a \x01 char. [^\1]匹配除\x01字符之外的任何字符。 This happens so because bracket expressions are meant to use exact literal characters or ranges of them .之所以发生这种情况,是因为括号表达式旨在使用精确的文字字符或它们的范围

In your case, you can remove all chunks of repeated chars with (\w)\1+ (while replacing with the same single char using the \1 backreference in the replacement pattern) and then extract the word chars:在您的情况下,您可以使用(\w)\1+删除所有重复字符块(同时使用替换模式中的\1反向引用替换相同的单个字符),然后提取单词字符:

set lst [regexp -all -inline {\w} [regsub -all {(\w)\1+} $str {\1}]];

See the online demo :查看在线演示

set str "sddgoooo";
set lst [regexp -all -inline {\w} [regsub -all {(\w)\1+} $str {\1}]];
puts $lst

Output:输出:

s d g o

Note that in other regex flavors, you could use a regex with a negative lookahead: (\w)(?!\1) (see this regex demo ).请注意,在其他正则表达式风格中,您可以使用带有负前瞻的正则表达式: (\w)(?!\1) (请参阅此正则表达式演示)。 The (?!\1) negative lookahead matches a location that is not immediately followed with Group 1 value. (?!\1)负前瞻匹配未紧跟第 1 组值的位置。 Unfortunately, Tcl regex flavor - although Tcl AREs generally support lookaheads - does not support lookaheads with backreference inside them.不幸的是,Tcl 正则表达式风格 - 尽管 Tcl ARE 通常支持前瞻- 不支持其中包含反向引用的前瞻。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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