iT邦幫忙

0

正規表達式取得月份

我將pattern設為

robot give me report (\d)\s*(year\s?=\s?([0-9]{4}) month\s?=\s?(0?[1-9]|1[012]))?

下列文本都可以正常取得月份

robot give me report 2 year=2021 month=1
robot give me report 2 year=2021 month=01
robot give me report 2 year=2021 month=2
robot give me report 2 year=2021 month=02
robot give me report 2 year=2021 month=3
robot give me report 2 year=2021 month=03
robot give me report 2 year=2021 month=4
robot give me report 2 year=2021 month=04
robot give me report 2 year=2021 month=5
robot give me report 2 year=2021 month=05
robot give me report 2 year=2021 month=6
robot give me report 2 year=2021 month=06
robot give me report 2 year=2021 month=7
robot give me report 2 year=2021 month=07
robot give me report 2 year=2021 month=8
robot give me report 2 year=2021 month=08
robot give me report 2 year=2021 month=9
robot give me report 2 year=2021 month=09

但下列文本,不知為何,月份都只能取到十位數字的1,個位數字都取不到。

robot give me report 2 year=2021 month=10
robot give me report 2 year=2021 month=11
robot give me report 2 year=2021 month=12

請問我該如何修正pattern,才能夠取得10、11、12?

https://regexr.com/5tg62

1 個回答

1
Han
iT邦新手 1 級 ‧ 2021-05-23 01:20:52
最佳解答
robot give me report (\d)\s*(year\s?=\s?([0-9]{4}) month\s?=\s?(1[012]|0?[1-9]))?

原本的 (0?[1-9]|1[012])
因為 10 提早符合了 0可有可無,接著1~9即可 的條件
把順序調換過來,應該就可以了

我要發表回答

立即登入回答