【问题标题】:Match first date in line with regex匹配第一个日期符合正则表达式
【发布时间】:2017-11-14 14:37:06
【问题描述】:

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

我的文字看起来像这样:

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

我只想要每行的第一个日期,所以不包括第二行的31.12.2017

我试过\K(([0-9]{2}).([0-9]{2}).([0-9]{4})),但这只会给我第二次约会,而不是第一次。

【问题讨论】:

  • 你有没有尝试过?请分享您的尝试,让我们不要重复同样的努力。
  • @WiktorStribiżew 抱歉,我现在尝试更新。我关于 Stackoverflow 的第一个问题 :)
  • @ThomasTallaksen 你可以使用^.*?\K\d+\.\d+\.\d+

标签: regex date notepad++


【解决方案1】:

代码

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,既然你先破解了它,我会要求你包括量词而不是任何数量的命中
  • @SriniV 谢谢,我打算使用特定的量词,但根据输入格式的性质,我认为这不是绝对必要的。如果指定量词对于解决他们的问题是不可或缺的,那么 OP 可以使用您的解决方案。
【解决方案2】:

完全归功于 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)

【讨论】:

  • {4}+ 等于 {4} 因为您无法以占有、贪婪或懒惰的方式完全匹配 4 个字符。它总是会尝试匹配 4 次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多