简体   繁体   中英

Better way to remove specific characters from a Perl string

I have dynamically generated strings like @#@!efq@!#! , and I want to remove specific characters from the string using Perl.

Currently I am doing something this (replacing the characters with nothing):

$varTemp =~ s/['\$','\#','\@','\~','\!','\&','\*','\(','\)','\[','\]','\;','\.','\,','\:','\?','\^',' ', '\`','\\','\/']//g;

Is there a better way of doing this? I am fooking for something clean.

You've misunderstood how character classes are used:

$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;

does the same as your regex (assuming you didn't mean to remove ' characters from your strings).

Edit: The + allows several of those "special characters" to match at once, so it should also be faster.

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p . In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation .

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta , and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//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