gpt4 book ai didi

javascript - 正则表达式匹配两组可选字符串之间的模式

转载 作者:行者123 更新时间:2023-11-28 17:28:27 24 4
gpt4 key购买 nike

我正在努力寻找一条与两组可选字符串之间的日期模式(并且仅该模式)匹配的规则 - birthday/birth/bday/born .

在匹配日期之前,输入中必须存在一个或多个字符串。

如果可能的话,还需要在单个正则表达式匹配操作中执行。这是我需要通过处理程序运行的几个表达式之一,该处理程序只需要一个表达式,并且不需要额外的逻辑。

这是一个例子:

I was born on 01/01-2001

应匹配01/01-2001

My bday was on 01-01-2001 which was the day I was born, obviously

应匹配01-01-2001

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})如果这些字符串出现在日期之前,它可以完美地匹配日期。如果我在日期之后有这些字符串,它不会匹配任何内容。

最佳答案

像这样简单的事情可以如你所愿吗?

/\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/));

<小时/>

根据评论进行更新。

如果要检查日期其中一个单词birth|bday|born,简单的解决方案可能是运行 2 个匹配

堆栈片段

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))/));

关于javascript - 正则表达式匹配两组可选字符串之间的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com