我正在努力寻找一条规则,该规则将与两组可选字符串-birthday/birth/bday/born
之间的日期模式(并且仅与该模式)匹配。
输入中必须包含一个或多个字符串,然后才能匹配日期。
如果可能,还需要在单个Regex匹配操作中执行。这是我需要通过处理程序运行的几个表达式之一,该处理程序只需要一个表达式,而没有其他逻辑的便利。
这是一个例子:
I was born on 01/01-2001
应匹配 2001年1月1日
My bday was on 01-01-2001 which was the day I was born, obviously
应匹配 2001年1月1日
01 01 2001 was my day of birth
应匹配 01 01 2001
Today’s date is 24/06/2018
不匹配
到目前为止,我有:(?<=.*born|birth|bday).*?([0-9]{2,4}[^A-Za-z0-9]+[0-9]{2,4}[^A-Za-z0-9]+[0-9]{2,4})
,如果这些字符串在日期之前,则可以完美地匹配日期。如果我在日期之后有这些字符串,则不匹配任何内容。
答案 0 :(得分:2)
像这样简单的事情可以按您的意愿工作吗?
/\d\d\/\d\d\/\d\d\d\d/
堆栈片段
var nr1 = "I was born on 01/01/2001"
var nr2 = "My bday was on 01/01/2001 which was the day I was born, obviously"
var nr3 = "01/01/2001 was my day of birth"
console.log(nr1.match(/\d\d\/\d\d\/\d\d\d\d/));
console.log(nr2.match(/\d\d\/\d\d\/\d\d\d\d/));
console.log(nr3.match(/\d\d\/\d\d\/\d\d\d\d/));
根据评论进行了更新。
如果要同时检查日期{em>和这两个单词birth|bday|born
,因为简单的解决方案是进行两次匹配
堆栈片段
var nr1 = "I was born on 01/01/2001"
var nr2 = "My bday was on 01/01/2001 which was the day I was born, obviously"
var nr3 = "01/01/2001 was my day of birth"
var nr4 = "This is a simple date 01/01/2001"
console.log(nr1.match(/(birth|bday|born)/) &&
nr1.match(/\d\d\/\d\d\/\d\d\d\d/));
console.log(nr2.match(/(birth|bday|born)/) &&
nr2.match(/\d\d\/\d\d\/\d\d\d\d/));
console.log(nr3.match(/(birth|bday|born)/) &&
nr3.match(/\d\d\/\d\d\/\d\d\d\d/));
console.log(nr4.match(/(birth|bday|born)/) &&
nr4.match(/\d\d\/\d\d\/\d\d\d\d/));
根据评论第二次更新。
将两个匹配项合并到一个正则表达式中,这篇文章既显示又给出了一些出色的解释:
堆栈片段
var nr1 = "I was born on 01/01/2001"
var nr2 = "My bday was on 01/01/2001 which was the day I was born, obviously"
var nr3 = "01/01/2001 was my day of birth"
var nr4 = "This is a simple date 01/01/2001"
console.log(nr1.match(/(?=.*(birth|bday|born))(?=.*(\d\d\/\d\d\/\d\d\d\d))/));
console.log(nr2.match(/(?=.*(birth|bday|born))(?=.*(\d\d\/\d\d\/\d\d\d\d))/));
console.log(nr3.match(/(?=.*(birth|bday|born))(?=.*(\d\d\/\d\d\/\d\d\d\d))/));
console.log(nr4.match(/(?=.*(birth|bday|born))(?=.*(\d\d\/\d\d\/\d\d\d\d))/));
答案 1 :(得分:1)
您可以先测试出生,生日或出生,然后匹配一组由单个字符分隔的三个数字。
/birth|born|bday/.test(str)? str.match(/\d+.\d+.\d+/)[0] : ""
str = "I was born on 01/01-2001"
console.log(/birth|born|bday/.test(str)? str.match(/\d+.\d+.\d+/)[0] : "")
str = "01 01 2001 was my day of birth"
console.log(/birth|born|bday/.test(str)? str.match(/\d+.\d+.\d+/)[0] : "")
str = "Today’s date is 24/06/2018"
console.log(/birth|born|bday/.test(str)? str.match(/\d+.\d+.\d+/)[0] : "")