使用Swift 2删除RegEx中的重复行

时间:2016-06-04 11:00:53

标签: regex xcode swift

我正在尝试使用Swift在Xcode中删除带有正则表达式的重复行。作为初学者,我在学习如何做到这一点时遇到了一些困难。

目前使用regEx,我正在尝试使用此代码(请注意,我使用两个反斜杠,其中一个用作Swift字符串的转义字符),改编自http://www.regular-expressions.info/duplicatelines.html:< / p>

let originalText = "Have a nice day \n\n Have a nice day"
let myPattern = "^(.*)(\\r?\\n\\1)+$"
let replacement = "\\1"

但似乎它在我的实现中不起作用。

1 个答案:

答案 0 :(得分:1)

描述

我将你的表达修改为:

(^[^\n]*$)(?:\n\1)+

替换为: \1

Regular expression visualization

此正则表达式将执行以下操作:

  • 查找重复的行

注意:您需要将\替换为\\并使用以下标记:多行,以便每行^$匹配,和全局选项,所以表达式在第一场比赛后继续。

实施例

现场演示

https://regex101.com/r/uJ9rS8/4

示例文字

Have a nice day
Have a nice day
fdaf
These are not the droids you are looking for
These are not the droids you are looking for
These are not the droids you are looking for

样本匹配

Have a nice day
fdaf
These are not the droids you are looking for

解释

NODE                     EXPLANATION
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    ^                        the beginning of a "line"
----------------------------------------------------------------------
    [^\n]*                   any character except: '\n' (newline) (0
                             or more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    $                        before an optional \n, and the end of a
                             "line"
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  (?:                      group, but do not capture (1 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \n                       '\n' (newline)
----------------------------------------------------------------------
    \1                       what was matched by capture \1
----------------------------------------------------------------------
  )+                       end of grouping
----------------------------------------------------------------------