如何用JavaScript正则表达式从无空格字符串中提取多个日期
Hey there! I see you're new to regex and struggling to pull those dates out of your unspaced strings where dates are wrapped by random non-date characters. Let's fix that right away.
The Basic Solution
Since your target dates all follow the standard YYYY-MM-DD format, we can use a straightforward regex to match any occurrence of this pattern, regardless of what characters are around it:
\d{4}-\d{2}-\d{2}
Add the global (g) flag to extract all matching dates instead of just the first one. Here's how it works in JavaScript (matching your example syntax):
// Example 1 const str1 = "From2017-01-01to2017-12-31_custom_EquityPurchaseAgreementMember_custom_FirstPaymentMember_currency_CNY"; const regex = /\d{4}-\d{2}-\d{2}/g; const res1 = str1.match(regex); // Returns: ['2017-01-01', '2017-12-31'] // Example 2 const str2 = "From2016-01-01to2016-12-31"; const res2 = str2.match(regex); // Returns: ['2016-01-01', '2016-12-31']
A More Strict Version (For Valid Dates)
If you want to avoid matching invalid dates (like 2017-13-01 or 2017-02-30), use this stricter regex that enforces valid months (01-12) and days (01-31), plus limits years to 19xx or 20xx (adjust if your date range is different):
/(?:19|20)\d{2}-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])/g
This will only pull dates that are actually calendar-valid, which is useful if your input might contain typos or malformed date strings.
Quick Breakdown
- Basic regex:
\d{4}-\d{2}-\d{2}simply targets theYYYY-MM-DDstructure, ignoring surrounding characters. - Strict regex:
(?:19|20)\d{2}: Ensures years fall in the 1900-2099 range(0[1-9]|1[012]): Restricts months to 01-12(0[1-9]|[12]\d|3[01]): Limits days to valid values (01-31)
内容的提问来源于stack exchange,提问作者Joseph Zapantis

