将第一个日期与正则表达式

时间:2017-11-14 14:37:06

标签: regex date notepad++

我正在尝试为Notepad ++编写一个正则表达式搜索字符串,它将匹配每行的第一个日期。

我的文字看起来像这样:

  

Nåskalfolkfåfred,iTromsø,09.09.2017 19:09MartinLægland,Publisertpånett。
  Nåskalfolkfåfred,iTromsø,09.09.2017,MartinLægland,31.12.2017Publisertpånett。
  Nåskalfolkfåfred,iTromsø,09.09.2017 19:09MartinLægland,Publisertpånett。

我只想要每行的第一个日期,所以在第二行排除31.12.2017

我已经尝试了\K(([0-9]{2}).([0-9]{2}).([0-9]{4})),但这只给了我第二个日期,而不是第一个日期。

2 个答案:

答案 0 :(得分:2)

代码

See regex in use here

^.*?\K\d+\.\d+\.\d+

结果

输入

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017, Martin Lægland 31.12.2017 Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

输出

09.09.2017
09.09.2017
09.09.2017

解释

  • ^在行首处断言位置
  • .*?任意次数匹配任何字符,但尽可能少
  • \K重置报告的匹配的起点。最终匹配中不再包含任何以前消费的字符
  • \d+\.\d+\.\d+匹配任意数字一次或多次,后跟一个点.,然后是相同的事物(任何数字一次或多次,后跟一个点.字面意思),然后是任何一位或多次数字

答案 1 :(得分:0)

完全归功于ctwheels。具有不同的风味,可以定义边界

^.*?\K[0-9]{2}+\.[0-9]{2}+\.[0-9]{4}+

<强>解释

^ asserts position at start of the string
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9 
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9 
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{4}+
{4}+ Quantifier — Matches exactly 4 times
0-9 a single character in the range between 0 - 9 
Global pattern flags
g modifier: global. All matches (don't return after first match)