我正在尝试编写一个正则表达式,以使用perl替换文本文件第一列中的字符串。我尝试了以下
foreach(@filecontents)
{
$_=~ s/($usersearch)\t|$usersearch\s\w+\t/$userreplace/gi;
}
这适用于我测试过的数据,但是有更好的方法吗?
您可以使用^
锚点(字符串锚点的开始),并且可以将模式稍微缩短一点:
$_ =~ s/^$usersearch(?:\s\w+)??\t/$userreplace/i;
??
您可以编写以下代码来代替使用惰性的量词:
$_ =~ s/^$usersearch(?:[^\S\t]\w+)?\t/$userreplace/i;
使用第二个版本,结果可能会更快一些。
说明:
(?:..) # is a non capturing group, it's only used to group elements
# together without capturing
?? # is the lazy version of the ? quantifier (zero or one time)
(?:..)?? # means "match the group only if needed"
# (vs (?:..)? # means "match the group if it is possible")
[^\S\t] # a character class that contains all white characters except the tab
# the ^ at the begining is used to negate the class, \S is all that
# is not a white character ( \s <=> [^\S] ), you only need to add \t
# to exclude it.
注意:如果您的变量$usersearch
可能包含正则表达式特殊字符,请不要忘记quotemeta
在模式中使用它之前使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句