Regular expression to remove some special chars

15,845

Solution 1

In ActionScript it goes like

yourString.replace(/[~%&\\;:"',<>?#\s]/g,"");

Same in Perl:

$_ = "~ % & \\ ; : \" ' , < > ? #";
s/[~%&\\;:"',<>?#\s]//g;
print; #prints nothing

Solution 2

[~%&\\;:"',<>?#\s]+

Solution 3

removes all whitespaces in $mystring using perl, you will need to add the other chars to in order to create your regex

$mystring = "...";
$mystring =~ s/\s//g;
Share:
15,845
Lotts
Author by

Lotts

Updated on June 08, 2022

Comments

  • Lotts
    Lotts almost 2 years

    I'm looking for a regular expression that can remove all the following characters from a string (and Whitespace too):

    ~ % & \ ; : " ' , < > ? #

    Can you help me? I'm coding in ActionScript 3.

  • Failed_Noob
    Failed_Noob almost 13 years
    How did you know OP uses perl?
  • Quick Joe Smith
    Quick Joe Smith almost 13 years
    The single- and double-quotes don't need to be escaped, at least in Perl.
  • Quick Joe Smith
    Quick Joe Smith almost 13 years
    This is a only 1/14th of the required solution. Very nearly a downvote.
  • YOU
    YOU almost 13 years
    @Quick, removed escapes, I was trying with sed on bash.
  • Quick Joe Smith
    Quick Joe Smith almost 13 years
    That's fair enough then since the OP has indicated neither a language or an environment. :)
  • Lotts
    Lotts almost 13 years
    Hi, thank you, I noticed it doesn't work without adding \g in the end
  • YOU
    YOU almost 13 years
    @Lotts, yeah, global flag will need it if you need to replace all instances.
  • Neerav Mathur Jazzy
    Neerav Mathur Jazzy about 5 years
    import re with open ('txt.txt', 'r') as fi: tm = fi.read().replace(',', '\n,') with open ('out_3.txt','w') as z: for j in tm: y = re.sub("[0-9 {} <> -,: _\. = +| \/]",'\n' , j) for gn in y: z.write(gn)
  • Petter Friberg
    Petter Friberg about 5 years
    I have tried to help some with formatting, but please check it, you can use 4 space to format code and ' to format in-line code. Please don't leave code in comments.
  • Yunnosch
    Yunnosch about 5 years
    StackOverflow does not require perfect English (or I myself would be pretty lost). But you are not seriously unable to do a little better, are you? Some capitalisation, a sprinkle of punctuation, more words which actually exist in English would really improve this post. Please?