我有一個字符向量。
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"
uj5u.com熱心網友回復:
您可以使用
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
請參閱正則運算式演示和此正則運算式演示,以及R 演示:
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)- 緊靠右側,必須有一個非空白字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338795.html
上一篇:將刻度名稱添加到persp3d圖
