我需要提取文本的第一部分,從大寫到第一個字母小寫。
例如,我有文本:“IV LONG TEXT HERE,現在文本 End HERE”
我想在這里提取“IV LONG TEXT”。
我一直在嘗試這樣的事情:
text <- "IV LONG TEXT HERE and now the Text End HERE"
stringr::str_extract_all(text, "[A-Z]")
但我在正則運算式上失敗了。
uj5u.com熱心網友回復:
您可以使用 str_extract 和一個模式來匹配單個大寫字符,并且可以選擇匹配空格和以另一個大寫字符結尾的大寫字符。
\b[A-Z](?:[A-Z ]*[A-Z])?\b
解釋
\b[A-Z]防止部分單詞匹配的單詞邊界,然后匹配單個字符 AZ(?:非捕獲組作為一個整體匹配[A-Z ]*[A-Z]匹配可選字符 AZ 或空格并匹配字符 AZ
)?關閉非捕獲組并使其可選\b一個詞的邊界
例子
text <- "IV LONG TEXT HERE and now the Text End HERE"
stringr::str_extract(text, "\\b[A-Z](?:[A-Z ]*[A-Z])?\\b")
輸出
[1] "IV LONG TEXT HERE"
uj5u.com熱心網友回復:
而不是str_extract使用str_replace或str_remove
library(stringr)
# match one or more space (\\s ) followed by
# one or more lower case letters ([a-z] ) and rest of the characters (.*)
# to remove those matched characters
str_remove(text, "\\s [a-z] .*")
[1] "IV LONG TEXT HERE"
# or match one or more upper case letters including spaces ([A-Z ] )
# capture as group `()` followed one or more space (\\s ) and rest of
#characters (.*), replace with the backreference (\\1) of captured group
str_replace(text, "([A-Z ] )\\s .*", "\\1")
[1] "IV LONG TEXT HERE"
uj5u.com熱心網友回復:
下面的代碼示例應該可以作業。
text <- "IV LONG TEXT HERE and now the Text End HERE"
stringr::str_extract_all(text, "\\w.*[A-Z] \\b")
輸出 :
[1] 'IV LONG TEXT HERE '
解釋 :
回傳出現零次或多次(.*)的任何單詞字符(\w),滿足大寫([AZ])范圍并以空格(\b)結尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476784.html
