const text ='Meeting at 3:30 PM';const timePattern =/(?:\d{1,2}:\d{2} [AP]M)/;const match = text.match(timePattern);const time = match ? match[0]:null;
console.log(time);// '3:30 PM'
当你需要匹配一个字符串,该字符串后面紧跟着另一个特定的模式时,可以使用正则表达式中的 x(?=y) 结构,其中 x 表示要匹配的模式,而 y 则表示后置条件。这种结构称为正向先行断言。以下是三个常见的业务例子:
const text ='Today is 2022-04-30, tomorrow will be 2022-05-01.';const datePattern =/\d{4}-\d{2}-\d{2}(?=[,.])/g;const matches = text.match(datePattern);
console.log(matches);// ['2022-04-30', '2022-05-01']
const text ='Contact us at (555) 123-4567 or email@example.com.';const phonePattern =/\(\d{3}\) \d{3}-\d{4}(?=\s|$)/g;const matches = text.match(phonePattern);
console.log(matches);// ['(555) 123-4567']
const text ='The price is $99.99, and it is on sale for $79.99.';const pricePattern =/(?<=\$)\d+\.\d{2}/g;const matches = text.match(pricePattern);
console.log(matches);// ['99.99', '79.99']
const text ='The user_id is user_123, and the user_name is user_john_doe.';const wordPattern =/(?<=\buser_)\w+/g;const matches = text.match(wordPattern);
console.log(matches);// ['123', 'john_doe']
const text ='The meeting starts at 09:30, and lunch break is at 12:00.';const timePattern =/(?<=\b\d{2}:)\d{2}/g;const matches = text.match(timePattern);
console.log(matches);// ['30', '00']