Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to remove specific characters from a Perl string

Tags:

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.

like image 717
Ron Avatar asked Mar 23 '12 23:03

Ron


People also ask

How do I remove a special character from a string in Perl?

Overview. We can use the chop() method to remove the last character of a string in Perl. This method removes the last character present in a string. It returns the character that is removed from the string, as the return value.

How do you get rid of a certain character in a string?

Python Remove Character from String using replace() We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

What does =~ do in Perl?

The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World" , so the expression is true.


2 Answers

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.

like image 166
Tim Pietzcker Avatar answered Sep 24 '22 07:09

Tim Pietzcker


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.

like image 35
ShinTakezou Avatar answered Sep 26 '22 07:09

ShinTakezou