使用正则表达式提取一些日期



我想用正则表达式从一些句子中提取一些日期。请帮助。

  • Ujjwal出生于1998年8月12日。这里摘录"2010年8月12日">

  • "Rahul于2003年6月30日开始营业"。这里摘录"六月三十日",2003年">

  • &;RK于2008年3月18日结婚&;节选"2008年3月18日">

  • Raj于2012年6月11日生下了孩子。摘录"2012年6月11日">

我想在Python中使用正则表达式提取这些日期。

我不是一个python的人,所以这是用JavaScript写的,但是正则表达式是相当独立于语言的。

var sentences = ["Ujjwal was born on 12th day of August 1998",
"Rahul started the business on 30th day of June, 2003",
"RK was married on 18 th .day of March 2008",
"Raj had a baby on 11 day of June, 2012"];
sentences.forEach((sentence) => {
var result = sentence.match(/on (.*)/);
if (result) {
console.log("result: ",result[1]);
}
});

一点也不优雅,但是它回答了你的问题,把"之后的所有内容都放在"上。还有,你的例子"第18天"。看起来有点奇怪。真的有人会在这里加个句号吗?

如果你想要更多的分解,有很多方法可以使用正则表达式,下面的表达式更健壮。但是,您正在解析语言,这可能会使事情复杂化。这个表达式适用于您提供的4个句子,但它可能不适用于第5个句子。

var sentences = ["Ujjwal was born on 12th day of August 1998",
"Rahul started the business on 30th day of June, 2003",
"RK was married on 18 th .day of March 2008",
"Raj had a baby on 11 day of June, 2012"];

sentences.forEach((sentence) => {
var result = sentence.match(/(w+)s+(.*)s+ons+(d+).*day.+((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Nov|Dec)w*)D*(d+)b/);
if (result) {
// console.log(result);
var name = result[1];
var what = result[2];
var day = result[3];
var month = result[4];
var year = result[5];
var date = month + " " + day + ", " + year;
console.log("Name: ", name);
console.log("What: ", what);
console.log("When: ", date);
}
});