tcl中正则表达式用得很多,往往一句代码能够做好几条其他语句才能做完的工作,高效快捷;
在处理string中逐行匹配的情况下往往是用参数-line,但其实-line相当于-lineanchor和-linestop。
在使用-lineanchor时的实践:
Changes the behavior of “^” and “$” (the “anchors”) so they match the beginning and end of a line respectively. This is the same as specifying the (?w) embedded option (see the re_syntax manual page).
ex.
% set dataRtn {Select the version of EVDEV to use
> 1. Enable EVDEV 1.0.0.0 (EVDEV_1_0_0_0)
2. Disable EVDEV (NO_EVDEV)
choice[1-2]:
*
* EVDEV Menu
*
Select the version of EVDEV_DEMO to use
> 1. Enable EVDEV_DEMO 1.0.0.0 (EVDEV_1_0_0_0_DEMO_1_0_0_0)
2. Disable EVDEV_DEMO (NO_EVDEV_DEMO)
choice[1-2]:
Select the version of EVDEV_DRV to use
> 1. Enable EVDEV_DRV 1.0.0.0 (EVDEV_1_0_0_0_DRV_1_0_0_0)
2. Disable EVDEV_DRV (NO_EVDEV_DRV)
choice[1-2]:}
我想将上面变量dataRtn中的以*开头的所有行删除。
最开始认为参数-lineanchor会匹配到每行的开头和结尾,不会存在贪婪匹配的问题:
% regsub -all -lineanchor {^\*.*$} $dataRtn {} dataRtn1
% set dataRtn1
Select the version of EVDEV to use
> 1. Enable EVDEV 1.0.0.0 (EVDEV_1_0_0_0)
2. Disable EVDEV (NO_EVDEV)
choice[1-2]:
%
发现错了,虽然参数-lineanchor会让^和$ 匹配行首和行尾,但是照样是贪婪匹配。最后的$ 会一直匹配到整个string的结尾。
于是使用下面的命令:
% regsub -all -lineanchor {^\*.*?$} $dataRtn {} dataRtn1
% set dataRtn1
Select the version of EVDEV to use
> 1. Enable EVDEV 1.0.0.0 (EVDEV_1_0_0_0)
2. Disable EVDEV (NO_EVDEV)
choice[1-2]:
---------------------------->这里是空行
---------------------------->这里是空行
---------------------------->这里是空行
Select the version of EVDEV_DEMO to use
> 1. Enable EVDEV_DEMO 1.0.0.0 (EVDEV_1_0_0_0_DEMO_1_0_0_0)
2. Disable EVDEV_DEMO (NO_EVDEV_DEMO)
choice[1-2]:
Select the version of EVDEV_DRV to use
> 1. Enable EVDEV_DRV 1.0.0.0 (EVDEV_1_0_0_0_DRV_1_0_0_0)
2. Disable EVDEV_DRV (NO_EVDEV_DRV)
choice[1-2]:
期望把空行也删除。
% regsub -all -lineanchor {^\*.*?\n$} $dataRtn {} dataRtn1
% set dataRtn1
Select the version of EVDEV to use
> 1. Enable EVDEV 1.0.0.0 (EVDEV_1_0_0_0)
2. Disable EVDEV (NO_EVDEV)
choice[1-2]:
显然不行,虽然$会匹配到行尾,但是似乎回车换行(\n)不是每行的结尾,所以匹配失败,导致一直匹配到string的末尾;
% regsub -all -lineanchor {^\*.*?\n} $dataRtn {} dataRtn1
% set dataRtn1
Select the version of EVDEV to use
> 1. Enable EVDEV 1.0.0.0 (EVDEV_1_0_0_0)
2. Disable EVDEV (NO_EVDEV)
choice[1-2]:
Select the version of EVDEV_DEMO to use
> 1. Enable EVDEV_DEMO 1.0.0.0 (EVDEV_1_0_0_0_DEMO_1_0_0_0)
2. Disable EVDEV_DEMO (NO_EVDEV_DEMO)
choice[1-2]:
Select the version of EVDEV_DRV to use
> 1. Enable EVDEV_DRV 1.0.0.0 (EVDEV_1_0_0_0_DRV_1_0_0_0)
2. Disable EVDEV_DRV (NO_EVDEV_DRV)
choice[1-2]:
这就是想要的结果了——不把\n当作结尾。