Regex: How could I avoid a character class?
perl, regex
Solution
Well, it's possible but I don't think I'd call it an improvement:
#!/usr/bin/env perl
use warnings;
use 5.012;
use utf8;
my $string = '_${Hello}?${World}!';
$string =~ s/(?=\P{Alphabetic})
(?=\P{Mark})
(?=\P{Decimal_Number})
(?=\P{Connector_Punctuation}) . /-/xgs;
say "<$string>";
With multiple positive lookaheads, they all have to succeed. So it matches one character (the `.`) that is not Alphabetic and not Mark and not Decimal_Number and not Connector_Punctuation, just like the negated character class would.
I added the `/s` modifier because the original regex would match a newline (although your sample string doesn't have one). I added `/x` so I could add some whitespace and break it over multiple lines.
What do you have against character classes, anyway?
Problem
Is it possible to write this without the `[^...]` but with using the `\P{...}`? ``` #!/usr/bin/env perl use warnings; use 5.012; use utf8; my $string = '_${Hello}?${World}!'; $string =~ s/[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}]/-/g; say "<$string>"; ```