1

从不同格式的两个日期生成正则表达式时间范围(YYYYMMDD)的最佳方法是什么,比如说(D.M.YYYY)?例如,三个不同的案例:

input date 1 = "20.11.2012"  
input date 2 = "27.11.2012"  
Wanted result = "2012112[0-7]"

input date a = "31.12.2011"  
input date b = "6.1.2012"  
Wanted result = "20111231\\|2012010[1-6]"  

input date x = "28.1.2012"  
input date y = "4.2.2012"  
Wanted result = "2012012[8-9]\\|2012013[0-1]\\|2012020[1-4]"

或者是否有比当前形式的“想要的结果”更好的正则表达式来获得相同的结果?在整个范围内一周就足够了,不需要超过 30 天。

4

1 回答 1

1

鉴于您的范围很小(7 天),简单地生成所有日期要容易得多。

这是一个执行此操作的脚本:

#!/bin/bash
fromDate="$1"
toDate="$2"

# break the dates into array so that we can easily access the day, month and year
IFS='.' read -a fromDateParts <<< "$fromDate"
IFS='.' read -a toDateParts   <<< "$toDate"

# loop until the days, months and years match on both dates
while [[ "${toDateParts[0]}" -ne "${fromDateParts[0]}" || "${toDateParts[1]}" -ne "${fromDateParts[1]}" || "${toDateParts[2]}" -ne "${fromDateParts[2]}" ]]
do
    # add the date to the pattern
    printf -v date "%d%02d%02d" "${fromDateParts[2]}" "${fromDateParts[1]}" "${fromDateParts[0]}"
    pattern="$pattern|$date"

    ((fromDateParts[0]++))

    # reset days and increment month if days exceed 31
    if [[ "${fromDateParts[0]}" -gt 31 ]]
    then
        fromDateParts[0]=1
        ((fromDateParts[1]++))

        # reset month and increment year if months exceed 12
        if [[ "${fromDateParts[1]}" -gt 12 ]]
        then
            fromDateParts[1]=1
            ((fromDateParts[2]++))
        fi
    fi
done

# finally add the toDate to the pattern
printf -v date "%d%02d%02d" "${toDateParts[2]}" "${toDateParts[1]}" "${toDateParts[0]}"
pattern="$pattern|$date"

# print the pattern, removing the first pipe
echo "${pattern#?}"

示例用法:

$ dateRange.sh 28.1.2012 4.2.2012
20120128|20120129|20120130|20120131|20120201|20120202|20120203|20120204

$ dateRange.sh 31.12.2011 6.1.2012
20111231|20120101|20120102|20120103|20120104|20120105|20120106

$ dateRange.sh 28.1.2012 4.2.2012
20120128|20120129|20120130|20120131|20120201|20120202|20120203|20120204
于 2012-11-07T09:28:16.883 回答