本文介绍了正则表达式在日期中添加连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中,我有一个如下所示的字符串

In R I have a character string that looks like the following

x <- c("20130603 00:00:03.102","20130703 00:01:03.103","20130804 00:03:03.104")

我想通过使用单个 gsub 命令(而不是使用 substrpaste,但我的有限regex 知识让我无法确定我需要做什么:

I would like to to look like the following by using a single gsub command (rather than using substr and paste, but my limited regex knowledge is frustrating me in working out what i need to do to do so:

y <- gsub([REGEX PATTERN TO MATCH],[REPLACEMENT PATTERN TO INSERT HYPHEN] ,x)

> y
[1] "2013-06-03 00:00:03.102" "2013-07-03 00:01:03.103" "2013-08-04 00:03:03.104"

在我的实际示例中,x 的长度为几百万,因此任何用于提高速度的微基准测试都会有所帮助.

In my actual example, x has a length of several million, so any microbenchmarking for speed improvements would be helpful.

一如既往,不胜感激.

推荐答案

以下应该有效:

gsub("(\\d{4})(\\d{2})(\\d{2})", "\\1-\\2-\\3", subject, perl=TRUE);

这篇关于正则表达式在日期中添加连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:19