[英]perl Regex replace for specific string length
我正在使用Perl做一些原型設計。
如果字符串恰好是2個字符,並且以“ e”結尾,則需要一個表達式用[ee]
替換e
。
le -> l [ee]
me -> m [ee]
elle -> elle : no change
我無法測試字符串的長度,我需要一個表達式來完成整個工作。
我試過了:
`s/(?=^.{0,2}\z).*e\z%/[ee]/g` but this is replacing the whole string
`s/^[c|d|j|l|m|n|s|t]e$/[ee]/g` same result (I listed the possible letters that could precede my "e")
`^(?<=[c|d|j|l|m|n|s|t])e$/[ee]/g` but I have no match, not sure I can use ^ on a positive look behind
編輯各位,您好極了,在網絡上搜索了數小時,而在發布后的幾分鍾內,我會在這里得到答案。
我嘗試了您所有的解決方案,並且它們在我的腳本中都可以正常運行,即以下示例:
my $test2="le";
$test2=~ s/^(\S)e$/\1\[ee\]/g;
print "test2:".$test2."\n";
-> test2:l[ee]
但是我正在從一個文本文件中加載這些正則表達式(使用Perl作原型,其思想是將其與任何實現正則表達式的語言重用):
例如,在我存儲的文本文件中(我用%在“ match”和“ replace”之間分割線):
^(\S)e$% \1\[ee\]
然后我解析並應用所有正則表達式:
my $test="le";
while (my $row = <$fh>) {
chomp $row;
if( $row =~ /%/){
my @reg = split /%/, $row;
#if no replacement, put empty string
if($#reg == 0){
push(@reg,"");
}
print "reg found, reg:".$reg[0].", replace:".$reg[1]."\n";
push @regs, [ @reg ];
}
}
print "orgine:".$test."\n";
for my $i (0 .. $#regs){
my $p=$regs[$i][0];
my $r=$regs[$i][1];
$test=~ s/$p/$r/g;
}
print "final:".$test."\n";
這種技術與我的其他正則表達式一起使用時效果很好,但是當我在替換中有$ 1或\\ 1時還不行...這就是我得到的:
final:\1\ee\
PS:您回答了最初的問題,我應該再開一個帖子嗎?
像s/(?i)^([az])e$/$1[ee]/
您可以使用以下匹配2個字符的正則表達式,然后將其替換為$1\\[$2$2\\]
:
^([a-zA-Z])([a-zA-Z])$
演示:
$my_string =~ s/^([a-zA-Z])([a-zA-Z])$/$1[$2$2]/;
您為什么不使用捕獲組進行替換?
`s/^([c|d|j|l|m|n|s|t])e$/\1 [ee]/g`
如果這些是您需要的字符,並且如果確實是一行之前或之后沒有空格的單詞,那么它將起作用。
這是另一個選擇,具體取決於您要查找的內容。 它將匹配由一個az字符組成的兩個字符串,然后在其自己的行上匹配一個'e',並在此字符串前后加上空格。 它將替換為單個z字符后跟'[ee]'
`s/^\s*([a-z])e\s*$/\1 [ee]/`
我會做這樣的事情
$word =~ s/^(\w{1})(e)$/$1$2e/;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.