Lea*_*ing 2 regex vim notepad++
我有一个存储在 .txt 文件中的 URL 列表(我使用的是 Windows 7)。
URL 的格式是这样的:
somesite1.com
somesite2.com
somesite3.com
sub1.somesite3.com
sub2.somesite3.com
sub3.somesite3.com
sub1.somesite3.net
sub1.somesite1.org
Run Code Online (Sandbox Code Playgroud)
在notepad++中,有一个选项可以使用“用正则表达式查找替换”,并且我相当确定gvim允许用户使用正则表达式(尽管我不完全确定如何在Gvim中使用它们)。
无论如何,我不知道要在查找和替换框中放入什么,以便它可以遍历文件的内容并只留下根域。如果操作正确,上面的示例列表将变成这样:
somesite1.com
somesite2.com
somesite3.com
somesite3.com
somesite3.com
somesite3.com
somesite3.net
somesite1.org
Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗?
对于 Vim 来说有几种方法(尾部斜杠也是可选的):
:%s/^.\+\.\ze[^.]\+\.[^.]\+$//
:%s/^.\+\.\([^.]\+\.[^.]\+\)$/\1/
Run Code Online (Sandbox Code Playgroud)
另请参阅:help /\ze
等\ze
,它们\zs
是 Vim 特定的并且非常有用。在 Vim 和 PCRE 中,还有有用的前瞻和后瞻断言。
我相信 Notepad++ 使用 PCRE;查找^.+\.([^.]+\.[^.]+)$
并将其替换为\1
应该可以(但我不使用 Notepad++)。
请注意,这不适用于使用第三级注册的国家/地区代码顶级域名 -example.com.au
将转换为com.au
. 然后有些国家/地区在某些规则下使用二级或三级注册...如果您关心这些情况,您将需要更多规则,并且完整的解析器将比正则表达式更简洁(尽管一如既往)使用正则表达式是可能的)。