簡體   English   中英

正則表達式以匹配兩組可選字符串之間的模式

[英]Regex to match a pattern between two sets of optional strings

我正在努力尋找一條規則,該規則將與兩組可選字符串之間的日期模式(僅該模式)相匹配- 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})可以完美匹配日期,前提是這些字符串位於日期之前。 如果我在日期之后有這些字符串,則不匹配任何內容。

這樣簡單的事情可以隨心所欲地工作嗎?

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

您可以先測試出生,生日或出生,然后匹配一組由單個字符分隔的三個數字。

/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] : "") 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM