2016-08-19 11 views
0

대부분 stringr 함수는 해당 stringi 함수의 래퍼입니다. str_replace_all 중 하나입니다. 그러나 내 코드는 stri_replace_all, 해당 stringi 함수와 함께 작동하지 않습니다.str_replace/stri_replace에서 캡처 된 그룹 사용 - stringi vs stringr

저는 낙타의 경우 (일부분)를 이격 된 단어로 변환하는 빠른 정규 표현식을 작성하고 있습니다.

str <- "thisIsCamelCase aintIt" 
stringr::str_replace_all(str, 
         pattern="(?<=[a-z])([A-Z])", 
         replacement=" \\1") 
# "this Is Camel Case ain't It" 

을 그리고 이것은하지 않습니다 :

나는이 작품 이유에 매우 의아해입니다

stri_replace_all(str, 
       regex="(?<=[a-z])([A-Z])", 
       replacement=" \\1") 
# "this 1s 1amel 1ase ain't 1t" 
+0

하나의 옵션은 'stri_replace_all 것 (STR, 정규식 = "( akrun

답변

5

stringr::str_replace_all의 출처를 보면캡처 그룹 참조를 $#으로 변환하려면 fix_replacement(replacement)이 호출됩니다. 그러나 stringi:: stri_replace_all에 대한 도움은 캡처 그룹에 $1, $2 등을 사용하는 것을 분명히 보여줍니다.

str <- "thisIsCamelCase aintIt" 
stri_replace_all(str, regex="(?<=[a-z])([A-Z])", replacement=" $1") 
## [1] "this Is Camel Case aint It" 
0

아래의 옵션은 두 경우 모두 동일한 출력을 반환해야합니다.

pat <- "(?<=[a-z])(?=[A-Z])" 
str_replace_all(str, pat, " ") 
#[1] "this Is Camel Case aint It" 
stri_replace_all(str, regex=pat, " ") 
#[1] "this Is Camel Case aint It" 

?stri_replace_all의 도움말 페이지에 따르면, $1, $2

stri_replace_all_regex('123|456|789', '(\\p{N}).(\\p{N})', '$2-$1') 

그래서 교체에 사용되는 제안 예는 우리가 \\1로 대체하는 경우가 작동합니다, 거기에 $1

stri_replace_all(str, regex = "(?<=[a-z])([A-Z])", " $1") 
#[1] "this Is Camel Case aint It"