【问题标题】:Include a space between words longer than n characters在长于 n 个字符的单词之间包含一个空格
【发布时间】:2021-12-12 12:43:40
【问题描述】:

我有一个字符向量。

x <- c('This is a simple text', 'this is a veryyyyyyyyyy long word', 'Replacethis andalsothis')

我想在长于n 个字符的单词之间插入一个空格。对于这个例子,我们可以考虑n = 10。我更喜欢regex 解决方案,但如果您认为还有其他选择,我不介意尝试。

我正在寻找的输出 -

c('This is a simple text', 'this is a veryyyyyyy yyy long word', 'Replacethi s andalsothi s')

我尝试使用the solution from this post 对我的数据进行必要的更改,但它没有提供所需的输出。

sub('(.{10})(?=\\S)//g', '\\1 ', x, perl = TRUE)
#[1] "This is a simple text"           "this is a veryyyyyyyy long word" "Replacethis andalsothis" 

【问题讨论】:

    标签: r regex string


    【解决方案1】:

    你可以使用

    gsub("\\b(\\w{10})\\B", "\\1 ", x) # If your words only consist of letters/digits/_
    gsub("(?<!\\S)(\\S{10})(?=\\S)", "\\1 ", x, perl=TRUE) # If the "words" are non-whitespace char chunks
    

    regex demothis regex demothe R demo

    x <- c('This is a simple text', 'this is a veryyyyyyyyyy long word', 'Replacethis andalsothis')
    gsub("\\b(\\w{10})\\B", "\\1 ", x)
    # => [1] "This is a simple text" "this is a veryyyyyyy yyy long word" "Replacethi s andalsothi s"
    
    x <- c("this is a veryyyyyyy|yyy long word")
    gsub("(?<!\\S)(\\S{10})(?=\\S)", "\\1 ", x, perl=TRUE)
    # => [1] "this is a veryyyyyyy |yyy long word"
    

    正则表达式匹配...

    • \b - 单词边界
    • (\w{10}) - 十个字符
    • \B - 仅当有另一个单词 char 立即出现在右侧时(因此,第十个单词 char 不是单词的结束字符)。

    • (?&lt;!\S) - 字符串开头或空格之后的位置
    • (\S{10}) - 第 1 组:十个非空白字符
    • (?=\S) - 紧靠右边,必须有一个非空白字符。

    【讨论】:

    • 感谢@Wiktor 的快速回答。我刚刚注意到在我的实际数据中,一些文本包含特殊符号,例如 'this is a veryyyyyyy|yyy long word'。在这种情况下,我希望输出为'this is a veryyyyyyy |yyy long word'。你认为正则表达式可以更新来处理吗?我尝试用. 替换\\w 以匹配任何字符,但显然它没有帮助。 gsub("\\b(.{10})\\B", "\\1 ", x)
    • @user16024709 是的,是gsub("(?&lt;!\\S)(\\S{10})(?=\\S)", "\\1 ", x, perl=TRUE),见this regex demo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2020-02-19
    • 2019-02-11
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多