perl regex用相应的替换替换多个匹配

时间:2014-06-25 07:54:41

标签: regex perl

enter image description here

我想像这样替换每场比赛:

fn.doc(
fn.collection(
fn.distinctValues(   # convert to camelcase also

我可以使用正则表达式找到匹配但不知道如何进行替换 这是正则表达式(\w+)(:)(\w+-\w+\()|(\w+)(:)(\w+\() http://regex101.com/r/kD9zG8

预期输出:

let $local-config := fn.doc($alert-action)/alert:action/alert:name
let $local-coll := fn.collection($uri)/alert:action/alert:name
let $global-coll := fn.distinctValues(fn.collection($global-uri)/alert:action/alert:name[../alert:name = 'ml_alert_action_17_01_action'])

请帮忙!

1 个答案:

答案 0 :(得分:4)

以下简单的正则表达式应该有效:

use strict;
use warnings;

my $data = do {local $/; <DATA>};

$data =~ s/(\w+):(\w+)-?(\w*)\(/$1.$2\u$3(/g;

print $data;

__DATA__
let $local-config := fn:doc($alert-action)/alert:action/alert:name
let $local-coll := fn:collection($uri)/alert:action/alert:name
let $global-coll := fn:distinct-values(fn:collection($global-uri)/alert:action/alert:name[../alert:name = 'ml_alert_action_17_01_action'])

输出:

let $local-config := fn.doc($alert-action)/alert:action/alert:name
let $local-coll := fn.collection($uri)/alert:action/alert:name
let $global-coll := fn.distinctValues(fn.collection($global-uri)/alert:action/alert:name[../alert:name = 'ml_alert_action_17_01_action'])

增强3+字

要处理2个以上的单词,您可以将正则表达式更改为以下内容:

$data =~ s{(\w+):([\w-]+)(?=\()}{"$1.".lcfirst join '', map ucfirst, split /-/, $2}eg;

或者,如果您的perl版本支持/r开关:

$data =~ s{(\w+):([\w-]+)(?=\()}{"$1.".$2=~s/-(.)/\u$1/gr}eg;