AutoHotKey如何使用正则表达式

时间:2016-03-03 17:39:27

标签: regex autohotkey

我有一个这样的字符串:

  

" NEW.APPLICATION SENT to OFFICE A 2/2/16-COMPLETED"

有没有办法在Autohotkey中使用Regex将日期提取为02/02/2016?我首先尝试匹配/符号,然后在它之前或之后获取数字。

myString := "NEW.APPLICATION SENT TO OFFICE A 2/2/16-COMPLETED"
FoundPos := RegExMatch(myString, "\/")
myString := SubStr(myString, (FoundPos -3),(FoundPos+8))
myString := RegExReplace(myString, "\D", "") ; This remove more than I wanted

但我不知道如何获得日期或月份。有时它们之间也可能有这样的空格。 "02 /02/16"

2 个答案:

答案 0 :(得分:1)

根据您的要求,这是一个非常严格的正则表达式:

(?:^|[^0-9])([0-2]?[1-9]|[1-3]0|31) *\/ *(0?[1-9]|1[0-2]) *\/ *((?:20)?[0-9]{2})(?:$|[^0-9])

答案 1 :(得分:1)

所以基本上你想要匹配这样的模式:
number (space) slash (space) number (space) slash (space) number

myString := "NEW.APPLICATION SENT TO OFFICE A 2 / 02 / 16-COMPLETED"

;This would do the job for the matching:
RegexMatch(myString, "(\d+)\s*/\s*(\d+)\s*/\s*(\d+)", match)
MsgBox, %match1%/%match2%/%match3%

;I prefer giving the regex results names though:
RegexMatch(myString, "O)(?P<month>\d+)\s*/\s*(?P<day>\d+)\s*/\s*(?P<year>\d+)", match)
MsgBox, % match.month "/" match.day "/" match.year

;now we just need to add zeroes in front of the day/month in case they are single digit
month := StrLen(match.month)=1 ? "0" match.month : match.month ;if single digit add a zero to the beginning, otherwise don't change it
day := StrLen(match.day)=1 ? "0" match.day : match.day ;if single digit add a zero to the beginning, otherwise don't change it
year := StrLen(match.year)=2 ? "20" match.year : match.year ;if year has only 2 digits add a 20 to the beginning

finalDate = %month%/%day%/%year%

MsgBox, %finalDate% ;output is 02/02/2016

我对它进行了测试,它几乎适用于任何事情:
2 / 02 / 162 / 02 /2016 2 /2/ 1602/2/162/2/ 162/02 / 2016等等。输出始终为02/02/2016

修改: 要替换原始字符串中的日期,只需添加以下行:

myString := RegexReplace(myString, "\d+\s*/\s*\d+\s*/\s*\d+", finalDate)
MsgBox, %myString%