简体   繁体   English

Perl正则表达式用于变量替换

[英]perl regex for variable substitution

I want to substitute variables marked by a "#" and terminated by a dot or a non-alphanumeric character. 我想替换以“#”标记并以点或非字母数字字符结尾的变量。 Example: Variable #name should be substituted be "Peter" 示例:应将变量#name替换为“ Peter”

abc#name.def => abcPeterdef
abc#namedef  => abc#namedef
abc#name-def => abcPeter-def

So if the variable is terminated with a dot, it is replaced and the dot removed. 因此,如果变量以点结尾,则将其替换并删除点。 Is it terminated by any non-alphanum character, it is replaced also. 它是否以任何非字母字符终止,也将被替换。

I use the following: 我使用以下内容:

s/#name\./Peter/i
s/#name(\W)/Peter$1/i

This works but is it possible to merge it into one expression? 这可行,但是可以将其合并为一个表达式吗?

There are several possible approaches. 有几种可能的方法。

s/#name(\W)/"Peter" . ($1 eq "." ? "" : $1)/e

Here we use /e to turn the replacement part into an expression, so we can inspect $1 and choose the replacement string dynamically. 在这里,我们使用/e将替换部分转换为表达式,因此我们可以检查$1并动态选择替换字符串。

s/#name(?|\.()|([^.\w]))/Peter$1/

Here we use (?| ) to reset the numbering of capture groups between branches, so both \\.() and ([^.\\w]) set $1 . 在这里,我们使用(?| )重置分支之间捕获组的编号,因此\\.()([^.\\w])设置$1 If a . 如果一个. is matched, $1 becomes the empty string; 匹配后, $1变为空字符串; otherwise it contains the matched character. 否则包含匹配的字符。

You may use 您可以使用

s/#name(?|\.()|(\W))/Peter$1/i

Details 细节

  • #name - matches the literal substring #name匹配文字子串
  • (?|\\.()|(\\W)) - a branch reset group matching either of the two alternatives: (?|\\.()|(\\W)) -与两个选项之一匹配的分支重置组
    • \\.() - a dot and then captures an empty string into $1 \\.() -一个点,然后将一个空字符串捕获到$1
    • | - or - 要么
    • (\\W) - any non-word char captured into $1 . (\\W) -捕获到$1任何非单词char。

So, upon a match, $1 placeholder is either empty or contains any non-word char other than a dot. 因此,在匹配时, $1占位符为空或包含除点以外的任何非单词char。

You can do this by using either a literal dot or a word boundary for the terminator 您可以通过使用文字点或单词边界作为终止符来执行此操作

Like this 像这样

s/#name(?:\.|\b)/Peter/i

Here's a complete program that reproduces the required output shown in your question 这是一个完整的程序,可以再现问题中显示的所需输出

use strict;
use warnings 'all';

for my $s ( 'abc#name.def', 'abc#namedef', 'abc#name-def' ) {

    ( my $s2 = $s ) =~ s/#name(?:\.|\b)/Peter/i;

    printf "%-12s => %-s\n", $s, $s2;
}

output 产量

abc#name.def => abcPeterdef
abc#namedef  => abc#namedef
abc#name-def => abcPeter-def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM