我想转换此数据格式
20140102
到
2014-1-2
使用正则表达式。
我试过的模式是这样的:
([0-9]{4})([0-9][0-9])([0-9][0-9])
我遇到的问题是删除0。
请帮助,谢谢!
答案 0 :(得分:5)
使用
(\d{4})(0)?((?(2)\d|\d\d))(0)?((?(4)\d|\d\d))
替换为\1-\3-\5
。
说明:
(\d{4}) // capture 4 digits in group 1 (year)
(0)? // next, consume a 0 if possible
( // now, if there was a 0, consume only one more digit
(?(2)\d
| // otherwise consume two digits
\d\d)
) // captured in group 3
(0)? // and the same thing again for the last two digits
(
(?(4)\d
|
\d\d)
)
答案 1 :(得分:2)
这可以通过使用锚点或单词边界来实现。
^(\d{4})(0)?([1-9])(\d*?)(0)?([1-9]\d?)$
OR
\b(\d{4})(0)?([1-9])(\d*?)(0)?([1-9]\d?)\b
如果输入仅包含您指定的确切日期格式,请尝试以下正则表达式。 Lookahead断言输入包含8个字符。
^(?=.{8}$)(\d{4})(0)?([1-9])(\d*?)(0)?([1-9]\d?)$
替换字符串:
$1-$3$4-$6
答案 2 :(得分:1)
答案 3 :(得分:0)
只是为了表明这不一定要用正则表达式解决,这里是另一种实现(在PHP中):
$values = [ '20140101', '20141212' ];
foreach ($values as $value)
var_dump(vsprintf('%d%02d-%d-%d', str_split($value, 2)));
结果:
string(8) "2014-1-1"
string(10) "2014-12-12"
答案 4 :(得分:0)
如果我有使用正则表达式,我可能会分两步执行此操作(例如在JavaScript中):
"20140102".replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3")
.replace(/-0/g, "-")
通过这种方式,每个步骤都可以通过简单的推理和验证。