使用正規表示式從 Notepad++ 上的每一行中提取並僅顯示年份

使用正規表示式從 Notepad++ 上的每一行中提取並僅顯示年份

我有這樣的字串

hack SIGN (2005) g$
5 Cm Per Second - Makoto Shinkai Collection (2007)
Abenobashi (2002) gd
Ai City - La Notte Dei Cloni (1986) dfg
AIKA (1997)
Anna Dai Capelli Rossi (1979) £$"£

我想在 Notepad++ 上顯示

2005
2007
2002
1986
1997
1979

我使用這個正則表達式,但似乎效果不佳

尋找:

\(\b(19|20)\d{2}\b\)

代替

r\n\1\1

但它回傳給我這樣的文字

hack SIGN r
2020 g$
5 Cm Per Second - Makoto Shinkai Collection r
2020
Abenobashi r
2020 gd
Ai City - La Notte Dei Cloni r
1919 dfg
..

所以這個正規表示式不能像預期的那樣運作

答案1

Ctrl按+H後請按照以下說明進行操作記事本++每行匹配一組 4 位數字並僅列印這些字符,從而獲得預期的結果。

  1. 找什麼: ^.*?(\d{4}+).*$

    在此輸入影像描述

  2. 用。 $1

  3. 搜尋模式: Regular expression
  4. Replace All

結果

2005
2007
2002
1986
1997
1979

在此輸入影像描述


更多資源

如何在Notepad++中使用正規表示式

錨點匹配行中的位置,而不是特定字元。

^

這與行的開頭相符(除非在集合內使用,請參見上文)。

$

這與行尾匹配。

字元的範圍或種類

[^...]

集合中字符的補集。

單字元匹配

., \c

匹配任何字元。如果您選取“. 匹配換行符”框,則點確實會執行此操作,從而使“任何”字元能夠跨多行運行。取消選取該選項後,然後 .只匹配行內的字符,而不匹配行結束字符(\r 和 \n)

乘法運算符

*

這會匹配 0 個或多個前一個字元的實例(盡可能多)。例如,Sa*m 符合 Sm、Sam、Saam 等。

*?

前一組中的零個或多個,但至少是:最短的匹配字串,而不是像「貪婪」* 運算子那樣的最長字串。因此,m.*?o 應用於文字 margin-bottom: 0;將匹配 margin-bo,而 m.*o 將匹配 margin-botto。

{n}

匹配它所應用到的元素的 n 個副本。

+

這會匹配前一個字元的 1 個或多個實例(盡可能多)。

團體

(...)

括號標示正規表示式的子集。與括號內容相符的字串( )可以重新用作反向引用或替換操作的一部分;請參閱下面的替換。

群組可以嵌套。

(?<some name>...), (?'some name'...),(?(some name)...)

字元的範圍或種類

\d

0-9 範圍內的數字,與[[:數字:]]


替補

$n, ${n}, \n

傳回與編號為 n 的子表達式相符的內容。不允許使用負索引。

答案2

  • Ctrl+H
  • 找什麼:^(?:.*?\(((?:19|20)\d{2})\).*|.*\R)$
  • 用。$1
  • 檢查環繞
  • 檢查正規表示式
  • 不要檢查. matches newline
  • Replace all

解釋:

^                   : beginning of line
  (?:               : start non capture group
    .*?             : 0 or more any character but newline, not greedy
    \(              : open parenthesis
      (             : start group 1
        (?:19|20)   : non capture group, 19 or 20
        \d{2}       : 2 digits
      )             : end group 1
    \)              : close parenthesis
    .*              : 0 or more any character but newline
   |                : OR
    .*              : 0 or more any character but newline
    \R?             : any kind of linebreak, optional
  )                 : end non capture group
$                   : end of line

給定如下輸入:

hack SIGN (2005) g$
5 Cm Per Second - Makoto Shinkai Collection (2007)
Abenobashi (2002) gd
Ai City - La Notte Dei Cloni (1986) dfg
AIKA (1997)
Anna Dai Capelli Rossi (1979) £$"£
123456 1234
(123) 4567

我們有:

2005
2007
2002
1986
1997
1979

相關內容