简体   繁体   English

Perl正则表达式匹配图释

[英]Perl regex matching emoticons

I'm trying to remove certain emoticons from a string, but I can't figure out how to match emoticons consisting of special characters and letters, for example :D or :-D (it works for emoticons like ":-)" ). 我正在尝试从字符串中删除某些表情,但是我不知道如何匹配由特殊字符和字母组成的表情,例如:D或:-D(它适用于“ :-)之类的表情) 。 I tried 我试过了

$message =~ s/\\:D//;

and few other variations, but nothing seems to work. 和其他几种变体,但似乎无济于事。 Where am I wrong? 我哪里错了?

EDIT: I was actually stupid and didn't realize I made all the letters lowercase before this command, so all the emoticons were already changed to ":d". 编辑:我实际上是愚蠢的,没有意识到我在执行此命令之前将所有字母都小写,因此所有表情符号已更改为“:d”。 Thanks for help. 感谢帮助。

use strict; use warnings;

my $s = "Hello ;-) :D :-D <3 World!";
my @emoticons = qw' ;-) :D :-D <3 ';

my $pat = join '|', map qr/\Q$_\E/, @emoticons;
$s =~ s/$pat//g;
$s =~ s/ +/ /g;

print "$s\n";

Output: 输出:

Hello World!

You can write some unit tests: 您可以编写一些单元测试:

sub assert_equals($$) {
  my ($expected, $actual) = @_;
  $expected eq $actual or die "expected <$expected>, got <$actual>\n";
}

sub no_smilies($) {
  my ($message) = @_;
  $message =~ s/:D\b//g;
  return $message;
}

sub test() {
  assert_equals("", no_smilies(":D"));
  ...
}

Then you can do the rest using trial and error. 然后,您可以使用反复试验来完成其余的工作。

You could try something like this for starters: 您可以为初学者尝试类似的方法:

s/[:;]-?[D)]//

Add characters into the [] classes as you discover new and interesting emoticons. 发现新的有趣表情符号后,将字符添加到[]类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM