2

I'm trying to extract the date from the following strings but to no avail.

const strs = [
    `X
       March 17th 2011
`,
    `X
       2011
`,
    `X
    March
       2011
`,
];

console.log(strs.map(s => 
  s.match(/X\s+([a-zA-Z]+?\s*[a-zA-Z0-9]+)?\s*(\d+)/))
);

The problem is with the first match, currently it is

[
    "X\n       March 17",
    "March",
    "17"
]

while it should be

[
    "X\n           March 17th 2011",
    "March",
    "17th",
    "2011"
]

Any help would be appreciated.

2
  • Removed that part, sorry. Commented Sep 29, 2020 at 22:46
  • Welcome to SO! Can the dates change beyond these 3 or is this the entire specification? In other words, are you guaranteed the format full_month_name day_ending_in_th 4_digit_year with the first two fields optional? Or is the logic that X is some sort of hint point and you want to capture anything up to the next 4 digit year after X? Commented Sep 29, 2020 at 22:46

1 Answer 1

1

You can use

/X(?:\s+([a-zA-Z]+))?(?:\s+([a-zA-Z0-9]+))?\s+(\d+)/g

See the regex demo. Details:

  • X - an X char
  • (?:\s+([a-zA-Z]+))? - an optional sequence of one or more whitespaces (\s+) and one or more ASCII letters (captured into Group 1)
  • (?:\s+([a-zA-Z0-9]+))? - an optional sequence of one or more whitespaces (\s+) and one or more ASCII letters or digits (captured into Group 2)
  • \s+ - 1+ whitespaces
  • (\d+) - Group 3: one or more digits

See a JavaScript demo below:

const strs = ["X\n           March 17th 2011\n", "X\n           2011\n", "X\n        March\n           2011\n"];
const rx = /X(?:\s+([a-zA-Z]+))?(?:\s+([a-zA-Z0-9]+))?\s+(\d+)/;
strs.forEach(s => 
  console.log( s.match(rx) )
);

Or, getting full values:

const strs = ["X\n           March 17th 2011\n", "X\n           2011\n", "X\n        March\n           2011\n"];
const rx = /X(?:\s+[a-zA-Z]+)?(?:\s+[a-zA-Z0-9]+)?\s+\d+/g;
strs.forEach(s => 
  console.log( s.match(rx).map(x => x.substr(1).trim().replace(/\s+/g, ' ') ))
);

Sign up to request clarification or add additional context in comments.

1 Comment

Just in case: the solution is confirmed to be working. See the demo in the answer, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.