简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM