如何删除重复字符并仅在 Perl 中保留唯一字符? [英] How do I remove duplicate characters and keep the unique one only in Perl?

查看:12
本文介绍了如何删除重复字符并仅在 Perl 中保留唯一字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除重复字符并仅保留唯一字符.例如,我的输入是:

How do I remove duplicate characters and keep the unique one only. For example, my input is:

EFUAHUU
UUUEUUUUH
UJUJHHACDEFUCU

预期输出为:

EFUAH
UEH
UJHACDEF

我遇到了 perl -pe's/$1//g while/(.).*/' 这很棒,但它甚至会删除输出中出现的单个字符.p>

I came across perl -pe's/$1//g while/(.).*/' which is wonderful but it is removing even the single occurrence of the character in output.

推荐答案

这可以使用 positive前瞻 :

perl -pe 's/(.)(?=.*?1)//g' FILE_NAME

使用的正则表达式是:(.)(?=.*?1)

  • . :匹配任何字符.
  • first () :记住匹配的单个字符.
  • (?=...) : +ve lookahead
  • .*? :匹配介于两者之间的任何内容
  • 1 :记住的匹配.
  • (.)(?=.*?1) :匹配并记住任何字符仅当再次出现在字符串后面.
  • s/// : Perl 的执行方式替换.
  • g:进行替换全球范围内......那就是不要停止之后第一次替换.
  • s/(.)(?=.*?1)//g :这将从输入字符串中删除一个字符仅当该字符稍后再次出现时在字符串中.
  • . : to match any char.
  • first () : remember the matched single char.
  • (?=...) : +ve lookahead
  • .*? : to match anything in between
  • 1 : the remembered match.
  • (.)(?=.*?1) : match and remember any char only if it appears again later in the string.
  • s/// : Perl way of doing the substitution.
  • g: to do the substitution globally...that is don't stop after first substitution.
  • s/(.)(?=.*?1)//g : this will delete a char from the input string only if that char appears again later in the string.

不会保持输入中字符的顺序,因为对于输入字符串中的每个唯一字符,我们都会保留其最后一个 出现,而​​不是第一次.

This will not maintain the order of the char in the input because for every unique char in the input string, we retain its last occurrence and not the first.

为了保持相对顺序不变,我们可以执行 KennyTM 在其中一条评论中所说的:

To keep the relative order intact we can do what KennyTM tells in one of the comments:

  • 反转输入行
  • 像以前一样进行替换
  • 在打印前反转结果

Perl 的一行代码是:

The Perl one line for this is:

perl -ne '$_=reverse;s/(.)(?=.*?1)//g;print scalar reverse;' FILE_NAME

由于我们在反转后手动进行 print,所以我们不使用 -p 标志,而是使用 -n 标志.

Since we are doing print manually after reversal, we don't use the -p flag but use the -n flag.

我不确定这是否是最好的单线器.如果他们有更好的选择,我欢迎其他人编辑此答案.

I'm not sure if this is the best one-liner to do this. I welcome others to edit this answer if they have a better alternative.

这篇关于如何删除重复字符并仅在 Perl 中保留唯一字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆