且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除重复的字符并仅在 Perl 中保留唯一的字符?

更新时间:2023-02-20 22:05:16

这可以使用 positive 来完成前瞻 :

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

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

  • . : 匹配任何字符.
  • first () : 记住匹配的单个字符.
  • (?=...) : +ve 前瞻
  • .*? : 匹配中间的任何内容
  • 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.