简体   繁体   中英

I would like to use regex to insert specific characters in a regex expression?

I'd like to be able to use regex in Perl to insert characters into words.

So that the word "TABLE" would become "T%A%B%L%E%"

Can I ask for the syntax for such a feat?

Many thanks

Break the string into characters then join them with what you want in between; also append that

my $res = ( join '%', split //, $string ) . '%';

A simple-minded way with regex

$string =~ s/(.)/$1%/g;

where with /r modifier you can preserve $string and return the changed string instead

my $res = $string =~ s/(.)/$1%/gr;

You can use this command,

echo TABLE|perl -pe 's/\w/$&%/g'

This outputs T%A%B%L%E%

OR (in case your data is contained in a file)

perl -pe 's/\w/$&%/g' test.pl

You may replace \\w with [a-zA-Z] if you just want to replace with alphabets as \\w matchs alphabets numbers and underscore.

You can use look-behind also

my $s = "table";

$s=~s/(?<=.)/%/g;

print $s;

If your version >5.14 you can use \\K

$s=~s/.\K/%/g;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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