Ganesh
Ganesh

Reputation: 515

Replace characters before a string match in Perl

I am trying to replace space/tab/or any character before a string match is found.

Given this input:

"1)apple. 2)blue pen. 3)black shirt. 4)red hat."

I want this output:

1)apple._2)blue pen._3)black shirt._4)red hat.

There is a fixed pattern, such as a digit followed by ), and before that I want a replacement.

Code:

$str = "1)apple. 2)blue pen. 3)black shirt. 4)red hat.";
print "before ==> $str \n";
$str =~ s/.(\d+)/_/g;
print "after ==> $str \n"; # o/p: 1)apple._)blue pen._)black shirt._)red hat.

Thanks

Upvotes: 0

Views: 986

Answers (2)

hwnd
hwnd

Reputation: 70742

You need to add the captured match $1 to the replacement side of your substitution operator.

$str =~ s/.(\d+\))/_$1/g;

You could also use a lookahead assertion here.

$str =~ s/.(?=\d+\))/_/g;

If you have a pattern with multiple digits, e.g 9)orange. 10)black shirt. the above will fail. Instead you can use a negated match, which will do the trick.

$str =~ s/[^\d](?=\d+\))/_/g;

Upvotes: 2

akawhy
akawhy

Reputation: 1608

change your pattern s/.(\d+)/_/g to s/.(\d+\))/_\1/g. the \1 in the pattern means the value you capture

update:

After turning on warnings, it suggests that it's better written \1 to $1

Upvotes: 1

Related Questions