复制与正则表达式匹配的文本

Mat*_*s F 2 regex notepad++ visual-studio

我有一个正则表达式,在文本文件中有几个匹配项.我想只将匹配复制到第二个文件.我不想复制包含匹配项的行:我只想要匹配的文本.

我没有找到在记事本++中执行此操作的方法(仅复制完整的行,而不仅仅是匹配).也不在Visual Studio搜索中.

有没有办法只复制匹配?也许在grepp或sed?

jay*_*ngh 8

你可以用两者来做.可以说我有以下文件 -

样本文件:

[jaypal:~/Temp] cat myfile 
this is some random number 424-555
and my cell is 111-222-3333
and 42555 is my zip code
Run Code Online (Sandbox Code Playgroud)

我想捕捉only numbersmyfile

使用sed:

有了sed可以使用的组合-n,并p沿着选项grouped pattern.

sed -n 's/.[^0-9]*\([0-9-]\+\).*/\1/p'
   |   |          |          |  |  ||
    ---            ----------    -- |
     |                  |        |  ---------> `p` prints only matched output. Since
     V                  V        V              we are suppressing everything with -n
 Suppress       Escaped `(`      \1 prints      we use p to invoke printing.
 output        start the group   first matched   
               you can reference  group
               it with \1. If you
               have more grouped
               pattern then they can
               be called with \2 ...
Run Code Online (Sandbox Code Playgroud)

测试:

[jaypal:~/Temp] sed -n 's/.[^0-9]*\([0-9-]\+\).*/\1/p' myfile 
424-555
111-222-3333
42555
Run Code Online (Sandbox Code Playgroud)

您只需将其重定向到另一个文件即可.

使用grep:

你可以使用 -

egrep -o "regex" filename
Run Code Online (Sandbox Code Playgroud)

要么

grep -E -o "regex" filename
Run Code Online (Sandbox Code Playgroud)

从手册页:

-E, --extended-regexp
    Interpret PATTERN as an extended regular expression (see below).

-o, --only-matching
    Show only the part of a matching line that matches PATTERN.
Run Code Online (Sandbox Code Playgroud)

测试:

[jaypal:~/Temp] egrep -o "[0-9-]+" myfile
424-555
111-222-3333
42555
Run Code Online (Sandbox Code Playgroud)

您只需将其重定向到另一个文件即可.

注意:显然这些都是简单的例子,但它传达了重点.