aa bb
aa bb

Reputation: 257

Matching a regex in javascript

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.

Upvotes: 2

Views: 119

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

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, ' ') ))
);

Upvotes: 1

Related Questions