[英]Include a space between words longer than n characters
我有一個字符向量。
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')
我已經嘗試通過對我的數據進行必要的更改來使用這篇文章中的解決方案,但它沒有提供所需的輸出。
sub('(.{10})(?=\\S)//g', '\\1 ', x, perl = TRUE)
#[1] "This is a simple text" "this is a veryyyyyyyy long word" "Replacethis andalsothis"
您可以使用
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
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 不是單詞的結束字符)。和
(?<!\\S)
- 字符串開頭或空格之后的位置(\\S{10})
- 第 1 組:十個非空白字符(?=\\S)
- 緊靠右側,必須有一個非空白字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.