首页 > 解决方案 > 在 TCL 语言中理解正则表达式有困难

问题描述

我是 TCL 语言的新手。我很难在 myFile.txt 中捕获数据。

我的文件.txt

set obj "{Hello}"
set obj "{Bye}"
set obj "{Nice}"
set obj "{Yoh}"

我想捕捉大括号内的单词,如下所示。

Hello, Bye, Nice, Yoh

如何在 TCL 中使用正则表达式。

标签: tclregexp-substr

解决方案


The first thing to try would be this simple thing:

regexp {\{(\w+)\}} $obj -> word

The key points:

  1. { and } are metacharacters inside Tcl's RE language variant, so they need to be escaped.
  2. The bit we want to extract (“non-empty word character sequence”, so \w+) needs to be captured and matched with a capture variable that comes afterwards: the -> is just a dummy variable for a capture that we want to ignore.
  3. Always put REs in Tcl inside curly braces unless you know exactly what you're doing. (When you know what you're doing, you'll know to put them in braces virtually always anyway.) This allows us to write REs without an inflammation of backslashes.

推荐阅读