正则表达式中的Perl正则表达式 [英] Perl regular expression inside regular expression
问题描述
我想询问是否可以在e修饰符的替换匹配表达式的RHS中放置另一个正则表达式。
例如,我想用相同数量的 - 替换$ foo中存储的单词,不区分大小写。
例如:
$ str =〜s /($ foo)/ $ temp = $ 1; $ temp〜= s /./-// gie;
但编译时会不断提供语法错误,而
$ str =〜s /($ foo)/ $ temp = $ 1; $ temp =---/ gie;
可以正常工作。
我想我没有正确逃避斜杠,任何想法?
您当然需要 e
修饰符才能使用
$ str ='banana';
$ foo ='na';
$ str =〜s / $ foo / $& =〜s#。# - #gr / ge;
print $ str;
请参阅在线Perl演示请注意,外部正则表达式使用 /
正则表达式分隔符,而内部正则表达式包含不同的定界符(<你可以在这里使用你最喜欢的两个。
e
修饰符是强制性的外部模式,你也需要将 r
修饰符传递给内部的一个,以避免修改只读值问题。
另请注意,在Perl v.5.20之前,您最好避免 $&
并将整个模式用(.. 。)
捕获组:
$ str =〜s /($ foo)/ $ 1 =〜 :S ## - #克/ GE;
^ ^ ^^
I would like to ask if it is possible to put another regular expression inside the RHS of a substitution match expression with the "e" modifier.
For example, I would like to replace any occurrence of the word stored in $foo with the same number of "-", case insensitive.
For example:
$str =~ s/($foo)/$temp = $1; $temp ~= s/./-//gie;
But it constantly gives syntax error when compiling, while
$str =~ s/($foo)/$temp = $1; $temp = "---"/gie;
does work.
I guess I did not properly escape the slashes, any ideas?
You certainly need the e
modifier to be able to use
$str = 'banana';
$foo = 'na';
$str =~ s/$foo/$&=~s#.#-#gr/ge;
print $str;
See the online Perl demo
Note that the outer regex uses /
regex delimiters, while the inner one contains different ones (you can use your favorite two here).
The e
modifier is obligatory with the outer pattern, and you also need to pass r
modifier to the inner one to avoid Modification of a read-only value issue.
Also note that before Perl v.5.20, you'd better avoid $&
and enclose the whole pattern with (...)
capturing group:
$str =~ s/($foo)/$1=~s#.#-#gr/ge;
^ ^ ^^
这篇关于正则表达式中的Perl正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!