user2128074
user2128074

Reputation: 193

Perl - Removing all special characters except a few

So i came across a Perl regex "term" which allows you to remove all punctuation. Here is the code:

$string =~ s/[[:punct:]]//g;.

However this proceeds to remove all special characters. Is there a way that particular regex expression can be modified so that for example, it removes all special characters except hyphens. As i stated on my previous question with Perl, i am new to the language, thus obvious things don't come obvious to me. Thanks for all the help :_

Upvotes: 1

Views: 2048

Answers (2)

Toto
Toto

Reputation: 91385

You may also use unicode property:

$string =~ s/[^-\PP]+//g;

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Change your code like below to remove all the punctuations except hyphen,

$string =~ s/(?!-)[[:punct:]]//g;

DEMO

use strict;
use warnings;
my $string = "foo;\"-bar'.,...*(){}[]----";
$string =~ s/(?!-)[[:punct:]]//g;
print "$string\n";

Output:

foo-bar----

Upvotes: 2

Related Questions