R:使用strsplit和perl REGEX语法提取大写字母和特殊字符

时间:2013-09-13 14:25:02

标签: regex r text-mining strsplit

如何仅使用以下大写字母和整个/提取[[:punct:]]/$[[:punct:]]

text <- c("This/ART ,/$; Is/NN something something/else A/VAFIN faulty/ADV text/ADV which/ADJD i/PWS propose/ADV as/APPR Example/NE ./$. So/NE It/PTKNEG makes/ADJD no/VAFIN sense/ADV at/KOUS all/PDAT ,/$, it/APPR Has/ADJA Errors/NN  ,/$; and/APPR it/APPR is/CARD senseless/NN again/ART ./$:")

# HOW to?
textPOS <- strsplit(text,"(   )|(?<=[[:punct:]]/\\$[[:punct:]])", perl=TRUE)
#                          ^^^ 
#                         extract only the "/" with the following capital letters
#                         and the whole "[[:punct:]]/$[[:punct:]]"

# Expected RETURN:
> textPOS
[1] "/ART" ",/$;" "/NN" "/VAFIN" "/ADV" "/ADV" "/ADJD" "/PWS" "/ADV" "/APPR" "/NE" "./$." "/NE" "/PTKNEG" "/ADJD" "/VAFIN" "/ADV" "/KOUS" "/PDAT" ",/$," "/APPR" "/ADJA" "/NN" ",/$;" "/APPR" "/APPR" "/CARD" "/NN" "/ART" "./$:"

谢谢! :)

1 个答案:

答案 0 :(得分:6)

您可以使用gregexprregmatches

regmatches(text, gregexpr('[[:punct:]]*/[[:alpha:][:punct:]]*', text))
# [[1]]
#  [1] "/ART"    "/NN"     "/VAFIN"  "/ADV"    "/ADV"    "/ADJD"   "/PWS"    "/ADV"    "/APPR"   "/NE"     "./$."    "/NE"    
# [13] "/PTKNEG" "/ADJD"   "/VAFIN"  "/ADV"    "/KOUS"   "/PDAT"   ",/$,"    "/APPR"   "/ADJA"   "/NN"     ",/$;"    "/APPR"  
# [25] "/APPR"   "/CARD"   "/NN"     "/ART"    "./$:"   

用正则表达式的话说:“找到以零或多个标点符号开头,后跟斜线后跟一个或多个字母或标点符号的内容。如果要包含数字,请切换到[:alnum:]


根据评论,如果你只想要正则表达式的大写字母:

regmatches(text, gregexpr('[[:punct:]]*/[[:upper:][:punct:]]*', text))

正如@eddi建议的那样,[A-Z][:upper:]大致相同。再次像@eddi建议的那样,这个正则表达式会捕获/ / LETTERS案例以及/ $ punct案例:

/[A-Z]+|[[:punct:]]/\\$[[:punct:]]