我正在嘗試將本文中的“o”替換為“?”:
? 指導部門的技術人員
? 作為專案負責人履行監督和管理職責
o 設定方向以確保目標和目的
o 選擇管理層和其他關鍵人員
o 與行政同事合作制定和執行公司計劃和部門戰略
o 監督部門年度財務計劃和預算的編制和執行
o 管理績效工資
? 履行分配的其他職責
因為這些在我試過的行的開頭
test<- sub(test, pattern = "o ", replacement = "? ") # does not work
test<- gsub(test, pattern = "^o ", replacement = "? ") # does not work
test<- gsub(test, pattern = "o ", replacement = "? ") # works but it also replaces to to t?
為什么“^o”不起作用,因為它只出現在每一行的開頭
uj5u.com熱心網友回復:
這都是一個值嗎?如果是這樣,請使用回溯查找o以下換行符或字串開頭:
test2 <- gsub(test, pattern = "(?<=\n|\r|^)o ", replacement = "? ", perl = TRUE)
cat(test2)
? Direct the Department’s technical
? Perform supervisory and managerial responsibilities as leader of the program
? Set direction to ensure goals and objectives
? Select management and other key personnel
? Collaborate with executive colleagues to develop and execute corporate initiatives and department strategy
? Oversee the preparation and execution of department’s Annual Financial Plan and budget
? Manage merit pay
? Perform other duties as assigned
或者,每行拆分為單獨的值,然后使用原始正則運算式:
test3 <- gsub(unlist(strsplit(test, "\n|\r")), pattern = "^o ", replacement = "? ")
test3
[1] "? Direct the Department’s technical"
[2] ""
[3] "? Perform supervisory and managerial responsibilities as leader of the program"
[4] ""
[5] "? Set direction to ensure goals and objectives"
[6] ""
[7] "? Select management and other key personnel"
[8] ""
[9] "? Collaborate with executive colleagues to develop and execute corporate initiatives and department strategy"
[10] ""
[11] "? Oversee the preparation and execution of department’s Annual Financial Plan and budget"
[12] ""
[13] "? Manage merit pay"
[14] ""
[15] "? Perform other duties as assigned"
uj5u.com熱心網友回復:
您在這里不需要任何回顧,^與(?m)標志一起使用:
test <- gsub(test, pattern = "(?m)^o ", replacement = "? ", perl=TRUE)
如果您指定標志,(?m)則重新定義錨點的行為,^這意味著“一行的開始” 。m
請參閱在線 R 演示:
test <- "? Direct the Department’s technical\n\no Set direction to ensure goals and objectives\n\no Select management and other key personnel"
cat(gsub(test, pattern = "(?m)^o ", replacement = "? ", perl=TRUE))
輸出:
? Direct the Department’s technical
? Set direction to ensure goals and objectives
? Select management and other key personnel
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533749.html
標籤:r正则表达式文本gsub
