2014-04-10 2 views
3

한다고 가정 나는 다음과 같은 텍스트가 :문장 (정규식, GSUB, gregexpr)의 첫 번째 단어를 대문자로

txt <- as.character("this is just a test! i'm not sure if this is O.K. or if it will work? who knows. regex is sorta new to me.. There are certain cases that I may not figure out?? sad! ^_^") 

내가이 문장의 첫 알파벳 문자를 대문자하고자합니다. ^|[[:alnum:]]+[[:alnum:]]+[.!?]+[[:space:]]*[[:space:]]+[[:alnum:]]

호출 gregexpr 반환에 :

> gregexpr("^|[[:alnum:]]+[[:alnum:]]+[.!?]+[[:space:]]*[[:space:]]+[[:alnum:]]", txt) 
[[1]] 
[1] 1 16 65 75 104 156 
attr(,"match.length") 
[1] 0 7 7 8 7 8 
attr(,"useBytes") 
[1] TRUE 

에 맞는 올바른 문자열의 인덱스입니다

은 나뿐만 일치하는 정규 표현식을 알아 냈어.

그러나 필요한 문자를 올바르게 대문자로 표시하려면 어떻게 구현해야합니까? 나는 내가 strsplit에 있어야한다고 생각하고있다. ..?

+0

미안, R에 대해 아무것도 몰라,하지만 당신은 일반적으로 CONCAT에서 [1]에 다음, 첫 번째 문자를 얻을 캡 및 것 (나머지 문자열을 포함하는 문자열) .. – UIlrvnd

+0

첫 번째 관련 질문은 r 특정 정보를 제공합니다. – UIlrvnd

답변

4

귀하의 regex이 귀하의 예를 위해 작동하지 않는 것 같습니다. 따라서 this question에서 하나를 훔쳤습니다.

txt <- as.character("this is just a test! i'm not sure if this is O.K. or if it will work? who knows. regex is sorta new to me.. There are certain cases that I may not figure out?? sad! ^_^") 
print(txt) 

gsub("([^.!?\\s])([^.!?]*(?:[.!?](?!['\"]?\\s|$)[^.!?]*)*[.!?]?['\"]?)(?=\\s|$)", "\\U\\1\\E\\2", txt, perl=T, useBytes = F) 
+0

이 작품! 난 정말 정규식에 브러시해야합니다! 감사! – Ray

1

rex을 사용하면이 유형의 작업을 조금 더 간단하게 만들 수 있습니다. 이것은 merlin2011이 사용한 것과 같은 정규식을 구현합니다.

txt <- as.character("this is just a test! i'm not sure if this is O.K. or if it will work? who knows. regex is sorta new to me.. There are certain cases that I may not figure out?? sad! ^_^") 

re <- rex(
    capture(name = 'first_letter', alnum), 
    capture(name = 'sentence', 
    any_non_puncts, 
    zero_or_more(
     group(
     punct %if_next_isnt% space, 
     any_non_puncts 
     ) 
    ), 
    maybe(punct) 
    ) 
) 

re_substitutes(txt, re, "\\U\\1\\E\\2", global = TRUE) 
#>[1] "This is just a test! I'm not sure if this is O.K. Or if it will work? Who knows. Regex is sorta new to me.. There are certain cases that I may not figure out?? Sad! ^_^" 
+0

이것은 정말 도움이 !! 나는 이것이 존재한다는 것을 전혀 몰랐다. – Ray

관련 문제