首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拆分字符串并在每个数字之前添加断线

拆分字符串并在每个数字之前添加断线
EN

Stack Overflow用户
提问于 2016-09-02 09:28:34
回答 2查看 95关注 0票数 2

所以我有向量,里面有参考书目

代码语言:javascript
复制
bibliography <- c("1. Cohen, A. C. (1955). Restriction and selection insamples from bivariate normal distributions. Journal
of the American Statistical Association, 50, 884–893.  2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.
Biometrika, 75, 11–20.  3.Arismendi, J. C. (2013). Multivariate truncated moments. Journal of Multivariate Analysis, 117, 41–75")

我想在表示编号的每一个数字(即1、2和3 )之前添加新的行/换行()。因此,如果我有50条书目,我想用向量自动拆分所有字符串,并在表示编号的每个数字之前添加断线。

到目前为止,我已经尝试过这样的方法(这不是最好的选择,因为第三个参考书目被忽略了):

代码语言:javascript
复制
   bibliography <- unlist(strsplit(bibliography, "  "))
    bibliography <- bibliography[-length(bibliography)] <- paste0(bibliography[-length(bibliography)], ' \\\\ ')

输出是这样的(,这是我想要的输出):

代码语言:javascript
复制
   [1] "1. Cohen, A. C. (1955). Restriction and selection in samples from bivariate normal distributions. Journal\nof the American Statistical Association, 50, 884–893. \\\\ "
    [2] "2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.\nBiometrika, 75, 11–20. \\\\ "

但这很费时,因为我不得不在每个数字(即1和2)之前手动添加双空间。这段代码才能正常工作。

我也看过这里

Add new line before every number in a string

Inserting Newline character before every number occurring in a string?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-02 10:14:28

这样你就可以得到你想要的地方了:

代码语言:javascript
复制
library(stringr)
library(dplyr)

# The first line adds the "~" character at the right break point
str_split(gsub("([1-9]\\.[]*[A-Z])","~\\1",bibliography), "~") %>%
unlist()  %>%
str_trim(side = c("both")) # Trimming potential spaces at the strings sides
票数 2
EN

Stack Overflow用户

发布于 2016-09-02 10:24:51

我尝试了一种基于正则表达式的方法

代码语言:javascript
复制
bibliography <- c("1. Cohen, A. C. (1955). Restriction and selection insamples from bivariate normal distributions. Journal of the American Statistical Association, 50, 884–893.  2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.
                  Biometrika, 75, 11–20.  3.Arismendi, J. C. (2013). Multivariate truncated moments. Journal of Multivariate Analysis, 117, 41–75")

out <- gsub("([^0-9][0-9]{1}\\.|^[0-9]{1}\\.)", "\t\\1",bibliography)
out <- unlist(strsplit(out, "\t"))
out <- gsub("^\\s+|\\s+$", "", out)
out <- out[-1]

你也许可以试一试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39288992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档