Sudhakar
Sudhakar

Reputation: 3094

perl regex for replacing multiple matches with corresponding replacements

enter image description here

I'd like to replace each match like this:

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

I'm able to find the matches using regex but not sure how to do replacements .Here's the regex (\w+)(:)(\w+-\w+\()|(\w+)(:)(\w+\() http://regex101.com/r/kD9zG8

Expected Output:

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'])

Please help!

Upvotes: 2

Views: 153

Answers (1)

Miller
Miller

Reputation: 35198

The following simple regex should work:

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'])

Outputs:

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'])

Enhancement for 3+ words

To handle more than 2 words, you can change the regex to the following:

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

Or if your perl version supports the /r switch:

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

Upvotes: 4

Related Questions