Filter non-typed characters

I am trying to filter out all the lines that I pass through my system, so I only send the correct characters.

The following are allowed.

az AZ "-" (hypen, 0x24) " " (space, 0x20) "'" (single quote, 0x27) "~" (tilde, 0x7E) 

Now I can find a regular expression that looks for characters in this set. But I need this regular expression that matches the strings from this set, so I can replace them with nothing.

Any ideas?

+4
source share
2 answers

Here is how you can do it. You marked Perl, so I will give you a perlish solution:

 my $string = q{That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st}; print $string . "\n"; $string =~ s{[^-a-zA-Z '~]}{}g; print $string . "\n"; 

Print

 That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st That is a ~ very cool ' but not realistic Tst 

To make it clear:

 $string =~ s{[^-a-zA-Z '~]}{}g; 

matches characters that are not [^..] inside brackets [ , ] and do not replace them with anything. The g flag at the end of a replacement replaces more than 1 character.

+7
source

A regular expression to match the strings you mentioned:

 [a-zA-Z\\-~]|\x27 

For more information see http://www.regular-expressions.info/quickstart.html

+1
source

Source: https://habr.com/ru/post/1494637/


All Articles