Home > OS >  How to get Word before matching word using regex Javascript?
How to get Word before matching word using regex Javascript?

Time:03-18

I've been trying to extract the value before the match. For example, I have the following sentences:

Florida 03/22/2022 04/05/2022 Bid Support Help Desk is glad to assist you

Florida 04/05/2022 Bid Support Help Desk is glad to assist you

In these examples, I want to extract anything before the last occurrence of the date. So, the last occurrence of date is: 04/05/2022 and I want to extract

03/22/2022
Florida

because it is behind the matching date. I have been able to get the last occurrence of the date by the following regex:

var Date = /(\b[0-9]{2}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{4}\b)(?![A-Z]\1)\b(?!.*\b\2\b)/gs.exec(String)[0];

Any guidance would be much appreciated.

CodePudding user response:

You can use

\S (?=\s \b(\d{2}([-/ .])\d{2}\2\d{4})\b(?!.*\b\d{2}([-/ .])\d{2}\3\d{4}\b))

See the regex demo. Details:

  • \S - one or more whitespaces
  • (?= - a positive lookahead that requires the following patterns to match immediately to the right of the current location:
  • \s one or more whitespaces
  • \b(\d{2}([-/ .])\d{2}\2\d{4})\b - Group1: word boundary, two digits, a separator (captured in Group 2), two digits, the same separator char as in Group 2, four digits, word boundary
  • (?!.*\b\d{2}([-/ .])\d{2}\3\d{4}\b) - a negative lookahead failing the match if there are zero or more chars other than line break chars as many as possible followed with word boundary, two digits, a separator (captured in Group 3), two digits, the same separator char as in Group 3, four digits, word boundary
  • ) - end of the positive lookahead.

const texts = ['Florida 03/22/2022 04/05/2022 Bid Support Help Desk is glad to assist you','Florida 04/05/2022 Bid Support Help Desk is glad to assist you'];
const reg = /\S (?=\s \b(\d{2}([-/ .])\d{2}\2\d{4})\b(?!.*\b\d{2}([-/ .])\d{2}\3\d{4}\b))/;
for (const text of texts) {
  console.log(text, '=>', text.match(reg)?.[0]);
}

  • Related